Sep
26
2012

C# Tutorials : How to add event handler in WPF

In this WPF tutorial we are going to see how to add event handler in WPF. From the previous article we learned that events are nothing but the actions performed by any control on UI or just the change of object state. We learned different types of event handling in WPF i.e. Tunnel, Bubble and Direct events. To get more basic idea of wpf event handling please read the article – Understanding event handling in WPF.

In the series of wpf tutorial, so far we learned to create a new wpf application, overview of WPF and WPF architecture. Now in this wpf tutorial we are going to discuss about two techniques to add event handler in wpf i.e. event handling in Windows Presentation Foundation.

One way is to handle the wpf event is through XAML itself and other way is to handle wpf event via managed code.

These two WPF event handling methods can be summarized as below –

  1. Event handling through XAML approach is called as Declarative Approach.
  2. Event handling using managed code is actually a conventional way as we normally do in WinForms. We call it as Code Approach.

To understand it more clearly let’s consider an example of buttons. In this wpf example, we would have two buttons. One is to demonstrate Declarative approach and other is to demonstrate Managed Code Approach. We would implement a code in respective Button_Click event of these two buttons.

  1. The button click event of first button will demonstrate the use of XAML i.e. Declarative approach.
  2. The button click event of second button will demonstrate the use of Conventional code approach i.e. managed code approach.

Steps to add event handler in WPF

  1. To add event handler in WPF, first create a new Simple WPF project with two button controls and one TextBlock control as shown in below screenshot.
    WPF Application demonstrates WPF event handling.
    WPF Application demonstrates WPF event handling.

    Change the Name of the first button as “btnXAMLApproach”, second button as “btnCodeApproach” and textbox as “txtDisplayMessage”.

  2. Once you change the names of these controls the XAML would look like below –
    <Button Content=”Declarative (XAML) Approach” Height=”45″
    HorizontalAlignment=”Left” Margin=”28,85,0,0″ Name=”btnXAMLApproach VerticalAlignment=”Top” Width=”167″ BorderThickness=”2″ />
    <Button Content=”Managed Code Approach” Height=”45″
    HorizontalAlignment=”Left” Margin=”211,85,0,0″ Name=”btnCodeApproach VerticalAlignment=”Top” Width=”159″ BorderThickness=”2″ />
    <TextBlock Height=”48″ HorizontalAlignment=”Left” Margin=”28,20,0,0″ Name=”txtDisplayMessage
    Text=”Welcome to http://www.csharptutorial.in/” VerticalAlignment=”Top” Width=”342″ TextAlignment=”Center” Focusable=”False” />
    </Grid>

    Here…

    1. btnXAMLApproach: button represents the XAML approach.
    2. btnCodeApproach: button represents the Code Approach.

Steps to add event handler in WPF using Declarative approach of event handling in WPF

Let’s first start with implementing Declarative event handling in WPF. Follow below steps to undestand it –

  1. Go to XAML view, locate XAML code for first button i.e. btnXAMLApproach and add a “Click” property in XAML. Follow below steps to add click event –
    1. We need to include button click event in XAML. To add click event, find BorderThickness=”2″ and after this attribute write Click=. Here .Net IDE will prompt to create a New Event Handler as shown in below screenshot.
      WPF Event handling - Adding Click event in XAML
      WPF Event handling – Adding Click event in XAML
    2. Hit Enter button to automatically create a new Event Handler Method for you in “MainWindox.xaml.cs” file. Now look at the XAML file new event handler will get added in Click property.
      BorderThickness=”2″ Click=”btnXAMLApproach_Click” /> 
    3. Go to “MainWindow.xaml.cs” file and you will see that the new event handler method is automatically get added.
      private void btnXAMLApproach_Click(object sender, RoutedEventArgs e)
      {
      } 

      This Method will always get fire when you click in XAML approach button.

  2. Now write a code in this Method to display a Text in TextBlock when you click on XAML approach button.
    txtDisplayMessage.Text = “Declarative (XAML) Approach Button Is Clicked..!!!”; 

    Your Declarative (XAML) approach button is ready. Now the next step is to write a code that demonstrates the Code Approach of event in WPF.

Steps to add event handler in WPF using Managed code approach of wpf event handling

Follow below steps –

  1. Go to “MainWindow.xaml.cs” file and enter following code immediate after “InitializeComponent();” –
    this.btnCodeApproach.Click += 
  2. As soon as you write above code, .Net IDE would prompt to press tab button to create new event handler.
    WPF Event handling - Adding Click event in XAML.cs
    WPF Event handling – Adding Click event in XAML.cs
  3. Press tab once, and it will again ask you to press Tab button to create an Event Handle Method –
    WPF Event handling - Code for Click event in XAML.cs
    WPF Event handling – Code for Click event in XAML.cs
  4. As soon as you pres the tab button, following code would get added in your xaml.cs file –
    void btnCodeApproach_Click(object sender, RoutedEventArgs e)
    {
          throw new NotImplementedException();
    }
  5. Now write a code in newly created event handler method to display text in textblock like below. All this code is in C#.net, because i think WPF & C# is a good combination.
    txtDisplayMessage.Text = “Managed Code Approach Button Is Clicked..!!!”; 

    That’s it. Save the files and we have completed the code part of both the approaches.

  6. So, the final code in xaml.cs file would be –
        public partial class MainWindow : Window
        {
            public MainWindow()
            {
                InitializeComponent();
                this.btnCodeApproach.Click += new RoutedEventHandler(btnCodeApproach_Click);
            }
            void btnCodeApproach_Click(object sender, RoutedEventArgs e)
            {
                txtDisplayMessage.Text = “Managed Code Approach Button Is Clicked..!!!”;
            }
            private void btnXAMLApproach_Click(object sender, RoutedEventArgs e)
            {
                txtDisplayMessage.Text = “Declarative (XAML) Approach Button Is Clicked..!!!”;
            }
        }
  7. Execute the application to see the result. Press F5 button and a window would open as shown in below screenshot –
    WPF Event handling
    WPF Event handling
  8. Click on “Declarative (XAML) Approach” button to display a message on textblock.
    WPF Event handling - XAML Declarative approach
    WPF Event handling – XAML Declarative approach
  9. Now click on “Managed Code Approach” button to demonstrates the Code Approach of Event Handling in WPF.
    WPF Event handling - Managed Code approach
    WPF Event handling – Managed Code approach

In this c# tutorial, we learnt to add event handler in WPF using two different techniques of Event Handling in WPF. The wpf events are further categorized as direct, tunnel and bubbling events.

I hope you enjoyed the article. If you find this article helpful, then could you please share the article on your social media?

Following few articles might be of your interest –

About the Author: Ashish Ramteke

Ashish Ramteke is a Software Professional, Part time blogger and founder of C# Tutorials, a popular blog on C#.Net. Ashish is having 6 years of work experience and an engineering degree in Computer Science and Engg.

Leave a comment