Get style from PhoneResources and apply to new ListBox - c#

I have this style in PhoneApplicationPage.Resources:
<phone:PhoneApplicationPage.Resources>
<data:CarListView x:Key="carCollection" />
<Style x:Key="ListBoxItemStyle1" TargetType="ListBoxItem">
<Setter Property="Template">
....
I am trying to add new ListBox with just one item to StackPanel. It just shows the name of class. I tried many ways. For example this:
ListBox lstBox = new ListBox();
CarListView view = new CarListView();
view.DataCollection.Add(new CarView("John", "Ferrari", "/Images/car_missing.jpg"));
lstBox.ItemsSource = view.DataCollection;
lstBox.Style = Application.Current.Resources["ListBoxItemStyle1"] as Style;
stackPanel.Children.Insert(0, lstBox);
Style and classes are alright. When I am not adding this in code but in xaml when page is loaded everything looks fine. How can I add new listbox from code with style from resources?

I have made a sample where i create it all in the code and loads the style from the pages resources as in your sample
The XAML:
<phone:PhoneApplicationPage.Resources>
<Style x:Key="myLBStyle"
TargetType="ListBoxItem">
<Setter Property="Background"
Value="Khaki" />
<Setter Property="Foreground"
Value="DarkSlateGray" />
<Setter Property="Margin"
Value="5" />
<Setter Property="FontStyle"
Value="Italic" />
<Setter Property="FontSize"
Value="14" />
<Setter Property="BorderBrush"
Value="DarkGray" />
</Style>
</phone:PhoneApplicationPage.Resources>
Then i have an empty stackpanel where i add the listbox when the user click on a button
The code behind file:
private void Test_Click_1(object sender, System.Windows.RoutedEventArgs e)
{
ListBox lstBox = new ListBox();
List<string> data = new List<string>() { "one", "two", "three" };
lstBox.ItemsSource = data;
lstBox.ItemContainerStyle = this.Resources["myLBStyle"] as Style;
MyStackPanel.Children.Insert(0, lstBox);
}

You have to use the ItemContainerStyle for the listboxitems, the Style is for the ListBox control!
<Grid x:Name="LayoutRoot" Background="White">
<Grid.Resources>
<Style x:Key="myLBStyle" TargetType="ListBoxItem">
<Setter Property="Background" Value="Khaki" />
<Setter Property="Foreground" Value="DarkSlateGray" />
<Setter Property="Margin" Value="5" />
<Setter Property="FontStyle" Value="Italic" />
<Setter Property="FontSize" Value="14" />
<Setter Property="BorderBrush" Value="DarkGray" />
</Style>
</Grid.Resources>
<ListBox Height="184" ItemContainerStyle="{StaticResource myLBStyle}" HorizontalAlignment="Left"
Margin="23,24,0,0" Name="listBox1" VerticalAlignment="Top" Width="204" >
<ListBox.Items>
<ListBoxItem Content="Item1" />
<ListBoxItem Content="Item2" />
<ListBoxItem Content="Item3" />
</ListBox.Items>
</ListBox>
</Grid>
Or in code:
listBox1.ItemContainerStyle = Application.Current.Resources["myLBStyle"] as Style;

Related

C#/WPF Main Window freezes when loading data into datagrid

guys I am currently working on a existing WPF Application build with Prism build and .NET 4.6. I have added a new Page which contains a few User Controls. In one of the User Controls I need to load a csv with a few hundred rows(always under thousand) into a datagrid.
Every time I load the data into the datagrid the whole Application freezes for a few seconds. I have tried to do the loading async with the dispatcher but the application freezes while loading. I have also tried to do it with a task but then I always got an exception("only UI Thread is allowed to change the observable collection")
Below my current async implementation which did not work, any help or idea is highly appreciated.
Thank you
Product XAML
<UserControl x:Class="Module.UserControls.Products"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:Module.UserControls"
xmlns:mvvm="http://prismlibrary.com/"
mvvm:ViewModelLocator.AutoWireViewModel="true"
mc:Ignorable="d"
d:DesignHeight="650" d:DesignWidth="800" Background="{DynamicResource Module.Background}" MaxHeight="1500">
<UserControl.Resources>
<Style TargetType="DataGridCell">
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<Style TargetType="TextBox">
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="FontSize" Value="16" />
<Setter Property="Foreground" Value="{DynamicResource Module.Textbox.Foreground}" />
<Setter Property="Margin" Value="5,5,5,5" />
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>
<Style TargetType="CheckBox">
<Setter Property="Margin" Value="5,5,5,5" />
<Setter Property="HorizontalAlignment" Value="Left" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<Style TargetType="Button">
<Setter Property="FontSize" Value="16" />
<Setter Property="FontWeight" Value="Normal" />
<Setter Property="Background" Value="{DynamicResource Module.Button.Background}" />
<Setter Property="Foreground" Value="White" />
</Style>
<Style TargetType="ComboBox">
<Setter Property="Margin" Value="5,5,5,5" />
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="IsSynchronizedWithCurrentItem" Value="True" />
</Style>
</UserControl.Resources>
<Grid>
<Grid Margin="0,20,0,0" Background="{DynamicResource Module.Block.Background}">
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="2*"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Grid.Row="0">
<TextBlock Text="Products" Style="{DynamicResource Module.H2}" />
</Label>
<ScrollViewer Grid.Column="0" Grid.Row="1" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" Margin="0,10,0,10" OverridesDefaultStyle="True" >
<ScrollViewer.Resources>
<Style TargetType="{x:Type ScrollBar}">
<Setter Property="Background" Value="LightGray"/>
</Style>
</ScrollViewer.Resources>
<DockPanel HorizontalAlignment="Stretch">
<DataGrid AutoGenerateColumns = "False" IsReadOnly="False" ItemsSource="{Binding ProductCollection, UpdateSourceTrigger=PropertyChanged, IsAsync=True, Mode=TwoWay}" HorizontalAlignment="Center"
Width="Auto" HorizontalContentAlignment="Center">
<DataGrid.Resources>
<Style TargetType="DataGridCell">
<Setter Property="Foreground" Value="Black" />
<Setter Property="FontSize" Value="16" />
<Setter Property="BorderBrush" Value="White" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Background" Value="{x:Null}" />
<Setter Property="BorderBrush" Value="{x:Null}" />
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header = "Position" Binding="{Binding Path=InProductPos, UpdateSourceTrigger=PropertyChanged}" Width="Auto" MinWidth="120" />
<DataGridTextColumn Header = "Layout Position" Binding="{Binding Path = InProductLayout, UpdateSourceTrigger=PropertyChanged}" Width="Auto" MinWidth="120"/>
<DataGridTextColumn Header = "Name" Binding="{Binding Path=InProductDescription, UpdateSourceTrigger=PropertyChanged}" Width="Auto" MinWidth="300"/>
<DataGridTextColumn Header = "Product Quantity" Binding="{Binding Path=InProductPieces, UpdateSourceTrigger=PropertyChanged}" Width="Auto" MinWidth="120"/>
<DataGridTextColumn Header = "Class" Binding="{Binding Path=InProductClass, UpdateSourceTrigger=PropertyChanged}" Width="Auto" MinWidth="120"/>
<DataGridTextColumn Header = "Product Part ID" Binding="{Binding Path=InProductPartID, UpdateSourceTrigger=PropertyChanged}" Width="Auto" MinWidth="120"/>
<DataGridTextColumn Header = "Number" Binding="{Binding Path=InProductNumber, UpdateSourceTrigger=PropertyChanged}" Width="Auto" MinWidth="120"/>
<DataGridTextColumn Header = "Part list Name" Binding="{Binding Path=InProductPartlistName, UpdateSourceTrigger=PropertyChanged}" Width="Auto" MinWidth="300"/>
</DataGrid.Columns>
</DataGrid>
</DockPanel>
</ScrollViewer>
</Grid>
</Grid>
</UserControl>
Button XAML
<UserControl x:Class="Module.UserControls.ButtonRow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:resx="clr-namespace:Module.Properties"
xmlns:local="clr-namespace:Module.UserControls"
xmlns:mvvm="http://prismlibrary.com/"
mvvm:ViewModelLocator.AutoWireViewModel="true"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVis" />
<Style TargetType="DataGridCell">
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
<Style TargetType="TextBox">
<Setter Property="VerticalContentAlignment" Value="Center" />
<Setter Property="FontSize" Value="16" />
<Setter Property="Foreground" Value="{DynamicResource Module.Textbox.Foreground}" />
<Setter Property="Margin" Value="5,5,5,5" />
<Style.Triggers>
<Trigger Property="Validation.HasError" Value="true">
<Setter Property="ToolTip"
Value="{Binding RelativeSource={x:Static RelativeSource.Self}, Path=(Validation.Errors)[0].ErrorContent}" />
</Trigger>
</Style.Triggers>
</Style>
<Style x:Key="StyleButtonWhite" TargetType="Button">
<Setter Property="Foreground" Value="White" />
</Style>
<Style x:Key="StyleButtonWhiteWhite" TargetType="Button">
<Setter Property="Foreground" Value="White" />
<Setter Property="Background" Value="{x:Null}" />
</Style>
<Style TargetType="Button">
<Setter Property="FontSize" Value="16" />
<Setter Property="FontWeight" Value="Normal" />
<Setter Property="Background" Value="{DynamicResource Module.Button.Background}" />
<Setter Property="Foreground" Value="White" />
</Style>
<Style TargetType="ComboBox">
<Setter Property="Margin" Value="5,5,5,5" />
<Setter Property="VerticalAlignment" Value="Center" />
</Style>
</UserControl.Resources>
<Grid>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" Margin="0,10,0,10">
<Button
Margin="12,0,12,0"
Command="{Binding LoadProductsCommand}"
Width="101" Height="40"
Style="{StaticResource StyleButtonWhite}"
Background="{DynamicResource Module.Button.Background}">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Import Products" Foreground="White" />
</StackPanel>
</Button>
</StackPanel>
</Grid>
</UserControl>
Part of the ViewModel
public DelegateCommand LoadProductsCommand => new DelegateCommand(LoadProducts, () => true);
private ObservableCollection<Product> _productCollection;
public ObservableCollection<Products> ProductCollection
{
get => _productCollection;
set
{
_productCollection = value;
OnPropertyChanged();
}
}
public async void LoadProducts()
{
if (Dispatcher.CurrentDispatcher.CheckAccess())
{
await Dispatcher.CurrentDispatcher.InvokeAsync(() =>
{
ProductCollection.AddRange(FileImport.ImportProducts());
});
}
}
Class of the collection
public string InProductPos
{
get => _inProductPos;
set
{
_inProductPos = value;
OnPropertyChanged();
}
}
public string InProductLayout
{
get => _inProductLayout;
set
{
_inProductLayout = value;
OnPropertyChanged();
}
}
public string InProductDescription
{
get => _inProductDescription;
set
{
_inProductDescription = value;
OnPropertyChanged();
}
}
public int InProductPieces
{
get => _inProductPieces;
set
{
_inProductPieces = value;
OnPropertyChanged();
}
}
public int InProductClass
{
get => _inProductClass;
set
{
_inProductClass = value;
OnPropertyChanged();
}
}
public int InProductPartID
{
get => _inProductPartID;
set
{
_inProductPartID = value;
OnPropertyChanged();
}
}
public string InProductNumber
{
get => _inProductNumber;
set
{
_inProductNumber = value;
OnPropertyChanged();
}
}
public string InProductPartlistName
{
get => _inProductPartlistName;
set
{
_inProductPartlistName = value;
OnPropertyChanged();
}
}
You may try something like shown below. It loads the Product collection in a background thread, and only adds them to the ObservableCollection in the UI thread.
public async Task LoadProducts()
{
var products = await Task.Run(() => FileImport.ImportProducts());
ProductCollection.AddRange(products);
}

Editable DatagridComboBoxColumn in WPF using C#

I'm using WPF DataGrid control with dynamic columns binding at run time.(DataGrid columns are dynamic)
Sample code is as below
.xaml is having below code
<Style TargetType="ComboBox" x:Key="ComboBoxEditingStyle">
<Setter Property="ItemsSource" Value="{Binding Path=DefinedFormatters}" />
<Setter Property="IsDropDownOpen" Value="False" />
<Setter Property="IsEditable" Value="True" />
<Setter Property="SelectedValue" Value="Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" />
<Setter Property="ItemTemplate">
<Setter.Value>
<DataTemplate>
<TextBlock Text="{Binding Path=Name}"></TextBlock>
</DataTemplate>
</Setter.Value>
</Setter>
</Style>
.xaml.cs file is having below code,
Binding theBinding = new Binding();
theBinding.Mode = BindingMode.TwoWay;
theBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
theBinding.ValidatesOnDataErrors = true;
DataGridComboBoxColumn colSuggestionList = new DataGridComboBoxColumn();
// theCollection is Collection<string>
colSuggestionList.ItemsSource = theCollection;
colSuggestionList.SelectedValueBinding = theBinding;
colSuggestionList.Visibility = Visibility.Visible;
colSuggestionList.EditingElementStyle = dgMainTemplate.FindResource("ComboBoxEditingStyle") as Style;
// dgMainTemplate is wpf DataGrid
dgMainTemplate.Columns.Add(colSuggestionList);
Column added properly, but I want to make this column as editable. User should be able to select either existing item from available list or enter a new value which is not exists in available list.
Here EditingElementStyle will add editable combobox but items are not showing in combobox until user selects any item.
Finally I got solution to this problem, Modified code is as below,
<Style x:Key="TextBlockComboBoxStyle" TargetType="{x:Type ComboBox}" BasedOn="{StaticResource {x:Type ComboBox}}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type ComboBox}">
<Label Content="{TemplateBinding Text}" Style="{StaticResource {x:Type Label}}" />
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<Style TargetType="ComboBox" x:Key="ComboBoxEditingStyle">
<Setter Property="ItemsSource" Value="{Binding Path=DefinedFormatters}" />
<Setter Property="IsDropDownOpen" Value="False" />
<Setter Property="IsEditable" Value="True" />
</Style>
.cs code is,
Binding theBinding = new Binding();
theBinding.Mode = BindingMode.TwoWay;
theBinding.UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged;
theBinding.ValidatesOnDataErrors = true;
DataGridComboBoxColumn colSuggestionList = new DataGridComboBoxColumn();
// theCollection is Collection<string>
colSuggestionList.ItemsSource = theCollection;
colSuggestionList.SelectedValueBinding = theBinding;
colSuggestionList.Visibility = Visibility.Visible;
colSuggestionList.EditingElementStyle = dgMainTemplate.FindResource("ComboBoxEditingStyle") as Style;
colSuggestionList.EditingElementStyle = dgMainTemplate.FindResource("ComboBoxEditingStyle") as Style;
colSuggestionList.ElementStyle = dgMainTemplate.FindResource("TextBlockComboBoxStyle") as Style;
// dgMainTemplate is wpf DataGrid
dgMainTemplate.Columns.Add(colSuggestionList);

After change wpf button IsMouseOver trigger color not work

this is my button code
public class MetroButton : Button
{
public static readonly DependencyProperty MoseOverBrushProperty;
public static readonly DependencyProperty PressedBrushProperty;
public MetroButton():base()
{
var resource = new ResourceDictionary
{
Source = new Uri("/Parking.Component.Ui;component/Styles/ButtonMetro.xaml",
UriKind.RelativeOrAbsolute)
};
Style = resource["ButtonMetro"] as Style;
//SetResourceReference(StyleProperty, Style);
}
static MetroButton()
{
MoseOverBrushProperty = DependencyProperty.Register("MoseOverBrush", typeof(Brush), typeof(MetroButton));
PressedBrushProperty = DependencyProperty.Register("PressedBrush", typeof(Brush), typeof(MetroButton));
}
public Brush MoseOverBrush
{
get { return (Brush)base.GetValue(MoseOverBrushProperty); }
set { base.SetValue(MoseOverBrushProperty, value); }
}
public Brush PressedBrush
{
get { return (Brush)base.GetValue(PressedBrushProperty); }
set { base.SetValue(PressedBrushProperty, value); }
}
}
and I use this style for my button
<Style x:Key="ButtonMetro" TargetType="{ x:Type LochalUI:MetroButton}">
<Setter Property="Foreground" Value="White" />
<Setter Property="MoseOverBrush" Value="#FF3F62FD"/>
<Setter Property="PressedBrush" Value="#FF000099"/>
<Setter Property="Background" Value="#FF6B9AFF"/>
<Setter Property="FontSize" Value="15" />
<Setter Property="FontFamily" Value="B Yekan" />
<Setter Property="SnapsToDevicePixels" Value="True" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type LochalUI:MetroButton}">
<Border x:Name="border" CornerRadius="4" Background="{TemplateBinding Background}">
<Grid>
<ContentPresenter x:Name="MyContentPresenter" Content="{TemplateBinding Content}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Margin="0,0,0,0" />
</Grid>
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter Property="Background" Value="{Binding Path=MoseOverBrush , RelativeSource={RelativeSource Self}}" />
<Setter Property="Foreground" Value="Black" />
</Trigger>
<Trigger Property="IsPressed" Value="True">
<Setter Property="Background" Value="{Binding Path=PressedBrush , RelativeSource={RelativeSource Self}}" />
<Setter Property="Foreground" Value="White" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
but the problem is there when i put color for my button background like below code:
<UI:MetroButton HorizontalAlignment="Left" Margin="10,10,0,0" VerticalAlignment="Top" Width="132" Height="107" Background="#FF09CD00" >
<Grid>
<Label Content="تنظیمات" HorizontalAlignment="Center" VerticalAlignment="Center" Padding="5,5,5,12" Foreground="White" Margin="5"/>
</Grid>
</UI:MetroButton>
the IsMouseOver changer color and IsPressed Triggers not work.
(I don't want use static resource in my setters)
Changing other properties has no effect just changing background made this problem.
I found the answer problem was in 2 place:
first one when we use trigger in
<ControlTemplate.Triggers/>
you have sure you set your setter set property on the currect object
and the secend one is in the binding we have change
Value="{Binding Path=MoseOverBrush , RelativeSource={RelativeSource Self}}"
to
Value="{Binding Path=MoseOverBrush , RelativeSource={RelativeSource TemplatedParent}}"
because MoseOverBrush is parrent property not the ControlTemplate property

Dynamically Create TextBlock and TextBox in XAML WPF

My Question Is I have a grid where number of TextBlock and TextBox will vary as per the ComboBox SelectedItem Change
So, what I want is that I have written a function for get the details of the TextBlock and TextBox.
C# Function
public void GetAdditionalAttributes()
{
using (Entities _entities = new Entities())
{
var attributeAll = (from c in _entities.AdditionalAttributeValues
where c.DeviceID == 35
select new AttributesClass { AttributeValue = c.AdditionalAttributeValue1, AttributeName = c.AdditionalAttribute.Name }).ToList();
DeviceAttributes = new ObservableCollection<AttributesClass>(attributeAll);
}
}
Now In the XAML I was trying:
<Style x:Key="AdditionalAttributeDisplay"
TargetType="Grid"
x:Name="AdditionalAttributeDisplay"
>
<Style.Resources>
<Style TargetType="ItemsControl">
<Setter Property="ItemsSource"
Value="{Binding DeviceAttributes}" />
<Style.Triggers>
<DataTrigger Binding="{Binding SelectedValue, ElementName=DeviceTypeComboBox}"
Value="1">
<Setter Property="ItemsSource"
Value="{Binding DeviceAttributes}" />
</DataTrigger>
</Style.Triggers>
</Style>
</Style.Resources>
</Style>
But I don't know how to create a TextBlock or TextBox with ItemSource binding.
You can change the ItemTemplate of your ItemsControl.
<Style TargetType="ItemsControl">
<Setter Property="ItemTemplate">
<Setter.Value>
<ItemContainerTemplate>
<Grid>
<TextBox Width="100" Height="20" Text={Binding AttributeName}/>
</Grid>
</ItemContainerTemplate>
</Setter.Value>
</Setter>
</Style>
In above snippet replace PropertyName with DeviceAttributes member you want

Cannot change the style of the selected item in a ListBox

I´m trying to change the focused/selected item of a ListBox. My application is based on this article.
At the moment I´m trying to set the ListBoxItem style via data templates:
<DataTemplate x:Key="ItemTemplate">
<TextBlock Text="{Binding}"
Foreground="Black"
FontFamily="Segoe UI"
FontSize="22"
HorizontalAlignment="Left"
Padding="15,10,0,0"
/>
</DataTemplate>
<DataTemplate x:Key="SelectedTemplate">
<TextBlock Text="{Binding}"
Foreground="Red"
FontFamily="Segoe UI"
FontSize="30"
HorizontalAlignment="Left"
Padding="15,10,0,0"
/>
</DataTemplate>
My idea was to switch between those templates using a trigger:
<Style TargetType="{x:Type ListBoxItem}" x:Key="ContainerStyle">
<Setter Property="ContentTemplate" Value="{StaticResource ItemTemplate}" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="ContentTemplate" Value="{StaticResource SelectedTemplate}" />
</Trigger>
</Style.Triggers>
</Style>
The ListBox looks like this:
<ListBox x:Name="valuesItemsCtrl"
BorderThickness="0"
ItemContainerStyle="{StaticResource ContainerStyle}"
Background="Transparent"
Tag="{Binding }">
<ListBox.AlternationCount>
<Binding>
<Binding.Path>Values.Count</Binding.Path>
</Binding>
</ListBox.AlternationCount>
<ListBox.ItemsSource>
<Binding>
<Binding.Path>Values</Binding.Path>
</Binding>
</ListBox.ItemsSource>
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
At the end I add the template to another ListBox:
<ListBox x:Name="tumblersCtrl"
BorderThickness="0"
Background="Transparent"
ItemsSource="{Binding Tumblers, ElementName=thisCtrl}"
ItemTemplate="{StaticResource TumblerTemplate}">
</ListBox>
Thanks for any help or hint!
Use ItemTemplate and data triggers:
<ListBox ItemsSource="{Binding}">
<ListBox.ItemContainerStyle>
<Style TargetType="{x:Type ListBoxItem}">
<Setter Property="IsSelected" Value="{Binding IsSelected}"/>
</Style>
</ListBox.ItemContainerStyle>
<ListBox.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}"
Foreground="Black"
FontFamily="Segoe UI"
FontSize="22"
HorizontalAlignment="Left"
Padding="15,10,0,0"
x:Name="tbName"/>
<DataTemplate.Triggers>
<DataTrigger Binding="{Binding IsSelected}" Value="True">
<Setter TargetName="tbName" Property="Foreground" Value="Red"/>
<Setter TargetName="tbName" Property="FontSize" Value="30"/>
</DataTrigger>
</DataTemplate.Triggers>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
where bound data is a collection of:
public class ViewModel : ViewModelBase
{
public String Name
{
get { return name; }
set
{
if (name != value)
{
name = value;
OnPropertyChanged("Name");
}
}
}
private String name;
public Boolean IsSelected
{
get { return isSelected; }
set
{
if (isSelected != value)
{
isSelected = value;
OnPropertyChanged("IsSelected");
}
}
}
private Boolean isSelected;
}
Window code-behind:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new[]
{
new ViewModel { Name = "John", IsSelected = true },
new ViewModel { Name = "Mary" },
new ViewModel { Name = "Pater" },
new ViewModel { Name = "Jane" },
new ViewModel { Name = "James" },
};
}
}
If you want to change the templates use DataTemplateSelector.
Dismiss your ContainerStyle and instead set the ListBox.ItemsTemplateSelector to your custom datatemplateselector as static resource.
You can find a detailed example in this link.
EDIT :
According to your comment you don't need DataTemplate just set these two properties in the Trigger:
<Style TargetType="{x:Type ListBoxItem}" x:Key="ContainerStyle">
<Setter Property="Foreground" Value="Black" />
<Setter Property="FontSize" Value="22" />
<Setter Property="FontFamily" Value="Segoe UI" />
<Setter Property="HorizontalAlignment" Value="Left" />
<Setter Property="Padding" Value="15,10,0,0" />
<Style.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Foreground" Value="Red" />
<Setter Property="FontSize" Value="30" />
</Trigger>
</Style.Triggers>
</Style>

Categories