Let’s see how we can make certain items in a ListBox look different from the others. Let’s create the ItemsSource and the Binding
public partial class Window1 : Window
{
private ObservableCollection<Student> _students = new ObservableCollection<Student>()
{
new Student { Name = "Svetlozar Angelov", Age = 22 }
, new Student { Name = "Ivan Ivanov", Age = 20 }
, new Student { Name = "Ivan Georgiev", Age = 23 }
, new Student { Name = "George Ivanov", Age = 18 }
, new Student { Name = "Georgi Georgiev", Age = 27 }
, new Student { Name = "Todor Ivanov", Age = 19 }
};
public ObservableCollection<Student> Students
{ get { return _students; } }
public Window1()
{
InitializeComponent();
listStudents.ItemsSource = Students;
}
}
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
and the xaml
<Window x:Class="WpfApplication4.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WpfApplication4">
<ListBox x:Name="listStudents">
<ListBox.DataContext>local:Window1</ListBox.DataContext>
</ListBox>
</Window>
Let’s create a DataTemplate for the ListBoxItem to show only the name of a student
<Window.Resources>
<DataTemplate x:Key="ItemTemplate">
<TextBlock Text="{Binding Path=Name}" />
</DataTemplate>
</Window.Resources>
<ListBox x:Name="listStudents" ItemTemplate="{StaticResource ItemTemplate}">
<ListBox.DataContext>local:Window1</ListBox.DataContext>
</ListBox>
Let’s suppose we want to change the background of those students, whose age is under 21. The first step is to create a bool property to make the check for us.
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
public bool UnderAge { get { return Age < 21 ? true : false; } }
}
Now we have to create a Style with a DataTrigger
<Style TargetType="{x:Type ListBoxItem}" x:Key="ItemStyle">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=UnderAge}" Value="True">
<Setter Property="Background" Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
and to apply it
<ListBox x:Name="listStudents"
ItemTemplate="{StaticResource ItemTemplate}"
ItemContainerStyle="{StaticResource ItemStyle}">
<ListBox.DataContext>local:Window1</ListBox.DataContext>
</ListBox>
There is nothing interesting about DataTriggers, just another example why Binding is so cool.