WPF list item, background color for different items

I have a WPF ListBox containing a list of objects from a specific class that I have. Something like that:

ObservableCollection<MyTable> tables = new ObservableCollection<MyTable>(); ... listTables.ItemsSource = tables; 

And XAML:

 <ListBox HorizontalAlignment="Left" Margin="8,10,0,0" Name="listTables" Width="153" ItemsSource="{Binding tables}" SelectionChanged="listTables_SelectionChanged" Height="501" VerticalAlignment="Top"> <ListBox.ItemTemplate> <DataTemplate> <Grid Margin="1"> <TextBlock Grid.Column="1" Text="{Binding tableName}" /> </Grid> </DataTemplate> </ListBox.ItemTemplate> </ListBox> 

Everything works perfectly. Now I want to have a different background for each item in the ListBox depending on the specific class property. For example, suppose the MyTable class has a property called isOccupied. If this flag is set for a specific item, I want it to have a red background in the ListBox, if it is not, then I want to have it with a green background. If the property changes, then the background should change accordingly.

Any tips on how to achieve this? I am looking at some information about ItemContainerStyle at the moment, but I'm relatively new to this, so I'm not sure if I am going the right way.

+8
c # wpf xaml listbox
source share
2 answers

You can achieve this using DataTrigger s

 <ListBox.ItemTemplate> <DataTemplate> <!-- Step #1: give an x:Name to this Grid --> <Grid Margin="1" x:Name="BackgroundGrid"> <TextBlock Grid.Column="1" Text="{Binding tableName}" /> </Grid> <!-- Step #2: create a DataTrigger that sets the Background of the Grid, depending on the value of IsOccupied property in the Model --> <DataTemplate.Triggers> <DataTrigger Binding="{Binding IsOccupied}" Value="True"> <Setter TargetName="BackgroundGrid" Property="Background" Value="Red"/> </DataTrigger> <DataTrigger Binding="{Binding IsOccupied}" Value="False"> <Setter TargetName="BackgroundGrid" Property="Background" Value="Green"/> </DataTrigger> </DataTemplate.Triggers> </DataTemplate> </ListBox.ItemTemplate> 

Keep in mind that if you expect these values ​​to be changed at runtime, your data item must properly implement and raise Property Change Notifications :

 public class MyTable: INotifyPropertyChanged //Side comment: revise your naming conventions, this is not a table. { private bool _isOccupied; public bool IsOccupied { get { return _isOccupied; } set { _isOccupied = value; NotifyPropertyChange("IsOccupied"); } } //.. Other members here.. } 
+13
source share
 <Style TargetType="ListBox" x:Key="myListBoxStyle"> <Style.Triggers> <DataTrigger Binding="{Binding SelectedItem.IsOccupied}" Value="True"> <Setter Property="Background" Value="Red" /> </DataTrigger> </Style.Triggers> </Style> 
0
source share

All Articles