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.


<Window x:Class="WPFStackPanelDemo.MainWindow"
   Title="MainWindow" Height="350" Width="525">
           <Style x:Key="MouseHoverHighlight">
              <EventSetter Event="TextBlock.MouseEnter" Handler="element_MouseEnter" />
              <EventSetter Event="TextBlock.MouseLeave" Handler="element_MouseLeave" />
       <TextBlock Width="200" Height="40" Style="{StaticResource MouseHoverHighlight}">
       Bring the Mouse over Me to see hover effect.

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


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()

        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.



Leave a Reply