WPF Property Trigger


With triggers you can change the value of a given property, once a certain condition changes. Triggers come in multiple flavors: Property triggers, event triggers and data triggers. They allow you to do stuff that would normally be done in code-behind completely in markup instead, which is all a part of the ongoing process of separating style and code.

There is an article at WPF Tutorial called Trigger, DataTrigger & EventTrigger.

Below is a simple example that is based on that article with a couple of small modifications.

Here is the XAML code. There is no C# code behind for this project. We add a trigger, which listens to theIsMouseOver property – once this property changes to True, we apply a setters: We change the Foreground to red.

<Window x:Class="PropertyTrigger2.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:PropertyTrigger2"
        mc:Ignorable="d"
        WindowStartupLocation="CenterScreen"
        Title="Property Trigger 2" Height="120" Width="350">
    <Grid Background="LemonChiffon">
        <TextBlock Text="Property Triggers - IsMouseOver - Red" FontSize="18" HorizontalAlignment="Center" 
                   VerticalAlignment="Center" TextDecorations="">
            <TextBlock.Style>
                <Style TargetType="TextBlock">
                    <Setter Property="Foreground" Value="Blue"></Setter>
                    <Style.Triggers>
                        <Trigger Property="IsMouseOver" Value="True">
                            <Setter Property="Foreground" Value="Red" />
                            <Setter Property="TextDecorations" Value="" />
                            <Setter Property="Background" Value="LemonChiffon"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </TextBlock.Style>
        </TextBlock>
    </Grid>
</Window>

When the user places the mouse over the text it turns red, as you can see in the screenshot below.