Winsmarts.com

Microsoft MVP

MVP Logo

Awarded the Microsoft MVP Award.

Hosted By

blah!bLaH!BLOG!!

WPF Styles: EventSetters

.. WPF styles, connecting events to handlers

Posted on 2/13/2007 @ 6:17 PM in #WPF | 0 comments | 3549 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.

Please post your comments:


Your feedback will be submitted for moderation, and will appear after it is approved.

Name:  
Email (optional): Your email address will not be posted.
URL (optional):
Comments: HTML will be ignored, URLs will be converted to hyperlinks  
Enter the text you see in the box:
 

Site designed and maintained by Sahil Malik | All Rights Reserved. ©2007 WinSmarts.com.