WPF Styles: EventSetters

Posted on 2/13/2007 @ 6:17 PM in #Silverlight and WPF by | Feedback | 33974 views

So, just to set the record straight, Stylesheets in WPF != Stylesheets in HTML.

Earlier, I had blogged about "Styles" in WPF. When we think of Styles, we think of styles we see in MS Word, or HTML. Yes those are styles, but those are only visual styles. WPF lets you go one step further, by creating, what I like to call, behavioral styles.

The typical syntax for setting a style looks a bit like this -  

<Style TargetType="TextBlock" x:Key="HeaderStyle">
  <
Setter Property="Foreground" Value="{StaticResource HeadingForeground}"
/>
  <
Setter Property="Background" Value="{StaticResource HeadingBackground}"
/>
</
Style
>

If you look at the C# equivalent of the above, it looks a bit like this -

So, something that inherits from the abstract class "SetterBase" can go into the SetterBaseCollection. Interestingly, there are two classes that inherit from that as shown below:

The first one, Setter, we have already looked at, but what is "EventSetter"?

Just as a setter connects a property with a value, an EventSetter connects an Event with an EventHandler. For instance, consider the following code -

<Window ...>
<
Window.Resources
>
<
Style TargetType="{x:Type Button}"
>
<
EventSetter Event="Click" Handler="ButtonOnClick"
/>
</
Style
>
</
Window.Resources
>
<
Button Margin="20,20,20,20"
>
Make Window Stay On Top
</Button
>
</
Window>

What happens when you click the button? Well, it tries and calls the ButtonOnClick event handler. So, if the event handler were to look a bit like this -

void ButtonOnClick(object sender, RoutedEventArgs args)
{
Topmost = !Topmost;
Button btn = args.Source as Button;
btn.Content = Topmost ? "Make Window Not Stay On Top" : "Make Window Stay On Top" ;
}

.. you would see that clicking on the button, toggles the "Stay On Top" Behavior of the window. NEAT!!

Another very very similar concept is "Triggers" in WPF.

Sound off but keep it civil:

Older comments..