Search content within the blog

Monday, December 5, 2011

EventSetters in Style

Event can also be attached inside style. Style provides EventSetter inside you can add EventName and attach appropriate handler for that event.

<Window.Resources>
<Style x:Key="MyButtonEvent" TargetType="Button">
<EventSetter Event="MouseEnter" Handler="Button_MouseEnter" />
<EventSetter Event="MouseLeave" Handler="Button_MouseLeave" />
</Style>
</Window.Resources>
<StackPanel>
<Button Name="Cut" Content="Cut"
Height="40" Width="150"
Style="{StaticResource MyButtonEvent}" />
</StackPanel>

private void Button_MouseEnter(object sender, MouseEventArgs e)
{
Button btn = sender as Button;
btn.Background = Brushes.Red;
}
private void Button_MouseLeave(object sender, MouseEventArgs e)
{
Button btn = sender as Button;
btn.Background = Brushes.Green;
}




In above example you can see that Button_MouseEnter and Button_MouseLeave handler is attached inside EventSetter of Style. Whenever mouse enter and leave it will change button background color.

No comments:

Post a Comment