As the name suggests, DataTrigger applies the property value to perform a set of actions on the data that has a data binding with the UI element. This is represented by the <DataTrigger> element.
Here's an example of writing a data trigger to a UI element:
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center"> <CheckBox Name="chkError" Content="Error" VerticalAlignment="Center"/> <TextBlock Margin="20, 0" FontSize="50"> <TextBlock.Style> <Style TargetType="TextBlock"> <Setter Property="Text" Value="Pass" /> <Setter Property="Foreground" Value="Green" /> <Style.Triggers> <DataTrigger Binding="{
Binding ElementName=chkError, Path=IsChecked}" Value="True"> <Setter Property="Text" Value="Fail" /> <Setter Property="Foreground" Value="Red" /> </DataTrigger> </Style.Triggers> </Style> </TextBlock.Style> </TextBlock> </StackPanel>
In the preceding example, we have two UI controls: a checkbox and a text block. The text block has a data trigger set to it, which has a data binding with the IsChecked property of the checkbox.
When you run the preceding example, we will see the following result based on the checked status of the CheckBox control:
When the property value matches True, it will trigger and set the text as Fail with a foreground color of red. In default cases (that is, when the value matches False), the normal case will execute and show the text Pass in the color green.