Triggers in WPF


Triggers are used to control the visual representation of a control like Button etc. Here we discuss Property Triggers.

Property Triggers are basically XAML condition statements which are used to check the state of a property to determine whether to use a specific style or we can say Setter value within the style of the Element.

<Style TargetType="{x:Type Button}">
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True" >
                   <Setter Property="FontWeight" Value="Bold" />
                    <Setter Property="Background" Value="Blue" />
                </Trigger>
            </Style.Triggers>
</Style>

Now look at this line:

<Style TargetType="{x:Type Button}">

This line sets the TargetType of the Style XML element to { x:Type Button } which means its target element type is Button.

After that we set the Trigger Property IsMouseOver to check the value. After that we set the Setter Property, which one is the actual property of the Button Control or Element on which we apply the trigger.

<Setter Property="FontWeight" Value="Bold" />
<
Setter Property="Background" Value="Blue" />

It sets the Background and the font of the Element.

After that we define the Button Control:

<Grid>
        <Button Height="21" Name="btn1">Triggers
       
</Button>
</Grid>

Here we define a Button (btn1) in the Grid.

TgtWPF1.gif

When we hover the mouse over it, the Trigger will Fire and the Button will be like this:

TgtWPF2.gif

Complete Program:

<Window x:Class="Triggers_In_WPF.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <Window.Resources>
        <Style TargetType="{x:Type Button}">
            <Style.Triggers>
                <Trigger Property="IsMouseOver" Value="True" >
                    <Setter Property="FontWeight" Value="Bold" />
                    <Setter Property="Background" Value="Blue" />
                </Trigger>
            </Style.Triggers>
        </Style>
    </Window.Resources>
    <Grid>
        <Button Height="21"
Name="btn1">Triggers
       
</Button>
    </Grid>
</
Window>

It can be only done when the trigger is in the True Condition.

<Trigger Property="IsMouseOver" Value="True" >

If we don't want to fire the Trigger, we can set it False.