Handle Events in Style using EventSetter in WPF Application

Updated on     Kisan Patel

In WPF, you can handle events to apply the styles on the controls using the EventSetter class. The Eventsetter class constructor invokes the specific event handler in response to routed events, which is applied to all elements that reference the Style class. An EventSetter class invokes the specified event handler in response to an event.

The beloe code shows the demonstration, how we can handle events using EventSetter class.

MainWindow.xaml

<Window x:Class="WPFStackPanelDemo.MainWindow"
   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
   Title="MainWindow" Height="350" Width="525">
    <Grid>
       <Grid.Resources>
           <Style x:Key="MouseHoverHighlight">
              <EventSetter Event="TextBlock.MouseEnter" Handler="element_MouseEnter" />
              <EventSetter Event="TextBlock.MouseLeave" Handler="element_MouseLeave" />
           </Style>
       </Grid.Resources>
       <TextBlock Width="200" Height="40" Style="{StaticResource MouseHoverHighlight}">
       Bring the Mouse over Me to see hover effect.
       </TextBlock>
    </Grid>
</Window>

To use an EventSetter class, you need to write the code for the event in the code-behind file:

MainWindow.xaml.cs

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;

namespace WPFStackPanelDemo
{
    /// 
    /// Interaction logic for MainWindow.xaml
    /// 
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void element_MouseEnter(Object sender, MouseEventArgs e) {
            ((TextBlock)sender).Background = new SolidColorBrush(Colors.Blue);
        }

        private void element_MouseLeave(Object sender, MouseEventArgs e)
        {
            ((TextBlock)sender).Background = new SolidColorBrush(Colors.Beige);
        }
    }
}

Now, run the application and move the mouse pointer over the TextBlock control on the window, the color of the TextBlock control changes.

EventSetter-demo-wpf


WPF

Leave a Reply