I have a very simple WPF application which displays a ComboBox which binds to a list of classes which represent people. Each \'Person\' object has a Name string field, and a
Use ItemContainerStyle
instead of ItemTemplate
:
<ComboBox ItemsSource="{Binding People}" Width="100" Height="20">
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem">
<Setter Property="Foreground" Value="Pink" />
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Sex}" Value="Male">
<Setter Property="Foreground" Value="Blue" />
</DataTrigger>
</Style.Triggers>
</Style>
</ComboBox.ItemContainerStyle>
</ComboBox>
You should use "Style" triggers instead of "TextBlock.Triggers"
use this XAML:
<Window x:Class="ComboBoxColour.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<StackPanel Orientation="Vertical">
<ComboBox ItemsSource="{Binding People}" Width="100" Height="20">
<ComboBox.ItemTemplate>
<DataTemplate>
<TextBlock Name="somePerson" Text="{Binding Path=Name}">
<TextBlock.Style>
<Style TargetType="TextBlock">
<Style.Triggers>
<DataTrigger Binding="{Binding Path=Sex}" Value="Male">
<DataTrigger.Setters>
<Setter Property="Foreground" Value="blue"/>
</DataTrigger.Setters>
</DataTrigger>
<DataTrigger Binding="{Binding Path=Sex}" Value="Female">
<DataTrigger.Setters>
<Setter Property="Foreground" Value="Pink"/>
</DataTrigger.Setters>
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
</StackPanel>
</Window>
Now you'll have blue for male and pink for female.