Style Triggers

In WinFx a lot of what you have to currently do in code to get WinForm controls to behave in a particular way can now be done with Style Triggers.  For example if you wanted a button on a form to change it’s color while the user pressed it you had to do code like the following.

        private void Button1_MouseDown(object sender, MouseEventArgs e)
        {
            button1.BackColor = Color.Red;
        }

        private void button1_MouseUp(object sender, MouseEventArgs e)
        {
            button1.BackColor = SystemColors.Control;
        }

In this case you need to set the buttons background color and then reset the color. With Style Triggers this type of thing can be done declaratively in XAML using a Style Trigger.

What the above code is doing is setting a style for all Buttons TargetType=”{x:Type Button}” and having the background color change to red when the button is pressed. The one amazing thing about Triggers is that the properties that are changed by them are automatically reset to their previous value when the triggered condition is no longer satisfied. Also Triggers are optimized for transient states which are expected to change and return to original state like the IsPressed property which changes as the user pressed and then releases the button.

Leave a Reply

Your email address will not be published. Required fields are marked *