#127 – Reacting to a Dependency Property Change Using Triggers

You can react to a dependency property’s value changing by using property triggers.  A property trigger allows you to set up a trigger that fires when a property has a specific value and when the trigger fires, set the value of a different property on the same object.

Because you can only fire the trigger based on discrete values, you often use property triggers that are associated with simple boolean properties.

Here’s an example where we change the Foreground color of a CheckBox control whenever the CheckBox is checked.

        <CheckBox Content="Check Me" HorizontalAlignment="Center">
            <CheckBox.Style>
                <Style TargetType="CheckBox">
                    <Style.Triggers>
                        <Trigger Property="IsChecked" Value="true">
                            <Setter Property="Foreground" Value="BlueViolet"/>
                        </Trigger>
                    </Style.Triggers>
                </Style>
            </CheckBox.Style>
        </CheckBox>

Notice that we can achieve the desired behavior without having to write any code, specifying the behavior entirely in XAML.

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #127 – Reacting to a Dependency Property Change Using Triggers

  1. Hugo Gu says:

    Is there any way to fire the trigger wherever the speicified property changed. Not for any discrete value.

  2. Pingback: #917 – Changing Something when an Expander Is Expanded | 2,000 Things You Should Know About WPF

  3. Pingback: #1,071 – How TextBox Reacts to Gaining Keyboard Focus | 2,000 Things You Should Know About WPF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: