I have an ObservableCollection<Object1>
type(Messages
in code below) which is bound to an ItemsControl
. Object1 is having two properties namely ErrMsg
and IsError
. I want to display the ErrMsg
in red colour if its an Error(i.e. if IsError
is true) otherwise Black.
<ItemsControl
Height="Auto"
Background="White"
ItemsSource="{Binding Messages}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock
Margin="5,0,0,0"
Text="{Binding ErrMsg}"
Width="Auto"
Foreground="Black">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Style.Triggers>
<DataTrigger
Binding="{Binding IsError}"
Value="true">
<Setter
Property="TextBlock.Foreground"
Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>
</StackPanel>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
Problem is that all the messages are always displayed in Black colour irrespective of IsError
value?
How can I achieve this?
That's because you specify Foreground="Black"
in your text block declaration. Local values (set on the element itself) override style values (including triggers).
To fix this, just move setting of black foreground to the style:
<TextBlock Margin="5,0,0,0"
Text="{Binding Value}"
Width="Auto">
<TextBlock.Style>
<Style TargetType="{x:Type TextBlock}">
<Setter Property="Foreground"
Value="Black"/>
<Style.Triggers>
<DataTrigger Binding="{Binding IsError}"
Value="true">
<Setter Property="Foreground"
Value="Red" />
</DataTrigger>
</Style.Triggers>
</Style>
</TextBlock.Style>
</TextBlock>