WPF-Data Trigger

Triggers basically enable you to change property values or act on them. Therefore, it allows you to dynamically change the appearance and/or behavior of controls without creating new controls.
Triggers are used to change the value of any given property when certain conditions are met. Triggers are usually defined in the style or document root that applies to a particular control. There are three types of triggers
Attribute triggers
Data triggers
- Event triggers

Data trigger
When the bound data satisfies certain conditions, the data trigger performs certain operations. Let's look at the following XAML code, which creates a check box and text block with some properties. When this check box is selected, it changes its foreground color to red.

<Window x:Class="trigger.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:trigger"
        mc:Ignorable="d"
        Title="MainWindow" Height="350" Width="525">
    <StackPanel HorizontalAlignment = "Center">
        <CheckBox x:Name = "redColorCheckBox" 
            Content = "Set red as foreground color" Margin = "20"/>
        <TextBlock Name = "txtblock" VerticalAlignment = "Center" 
            Text = "Event Trigger" FontSize = "24" Margin = "20">
            <TextBlock.Style>
                <Style>
                    <Style.Triggers>
                        <DataTrigger Binding = "{Binding ElementName = redColorCheckBox, Path = IsChecked}" 
                        Value = "true">
                            <Setter Property = "TextBlock.Foreground" Value = "Red"/>
                            <Setter Property = "TextBlock.Cursor" Value = "Hand" />
                        </DataTrigger>
                    </Style.Triggers>
                </Style>
            </TextBlock.Style>
        </TextBlock>
    </StackPanel>
</Window>

When the above code is executed, it generates the following windows:

When this check box is checked, the foreground color of the text block will turn red.

Keywords: Attribute Windows

Added by ThisIsMyName on Sat, 05 Oct 2019 12:40:25 +0300