Skip to main content

WPF Event Handling

Introduction

Event handling in WPF is different as compare to Winform and Asp.net, this article describes the type of events WPF supports.

Getting Started

As compare to classic WinForm and ASP.NET, event handling is different in WPF. Because Winform and ASP.NET support Direct Events and WPF supports Routed Events, in direct event if an event is raised by any control, that event must be handled by the same control itself. even if the event is raised in a particular control, it is not necessary to handle on that exact target control itself, instead it can be handled in it’s any one of the parent element also. This type of events are called Routed Events

Routed event can be attached in any control even that control does not have that events declared on that class, Hence Routed Events are called Attached Events. For example, WPF Grid does not have Click event, but if the Grid has button inside, then the click event of the button can be handled by the Stack panel.

Event Attachment syntax in XAML

 <Grid Name="mygrid" Button.Click="Grid_Click">  
  </Grid>  

Event Attachment syntax in Code Behind

 myGrid.AddHandler(Button.ClickEvent, new RoutedEventHandler(Grid_Click));  

Example

 //In xaml  
 <Grid Name="mygrid" Button.Click="Grid_Click">  
     <Button x:Name="button" Content="Attached Event Example" HorizontalAlignment="Left" Margin="199,136,0,0" VerticalAlignment="Top" Width="104" Height="53"/>  
   </Grid>  
 //Code behind  
 myGrid.AddHandler(Button.ClickEvent, new RoutedEventHandler(Grid_Click));  
 // Handling Event  
 private void Grid_Click(object sender, RoutedEventArgs e)  
 {  
       MessageBox.Show("Button Click event handled in grid");  
  }  

Types of Routed Event

Based on the routing strategies WPF Routed Event classified into following three types.
  1. Bubbling Event:

    When this event is raised, first the event will be raised in the target element and then it will be bubbling up to the top most parent, that means event handlers on the event source are invoked first and the event then routes to successive parent elements until reaching the element tree root. Most routed events use the bubbling routing strategy. Bubbling routed events are generally used to report input or state changes from distinct controls or other UI elements.

    MouseDown and MouseUp are most used bubbling events in WPF, see the example for more

     <Grid Name="mygrid" MouseDown="mygrid_MouseDown">  
         <TextBlock x:Name="textBox" HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" MouseDown="TextBlock_MouseDown" Text="Bubbling event example" VerticalAlignment="Top" Width="120" Margin="193,154,0,0"/>  
       </Grid>  
    
      private void mygrid_MouseDown(object sender, MouseButtonEventArgs e)  
      {  
           MessageBox.Show("Mouse down handled in grid");  
      }  
      private void TextBlock_MouseDown(object sender, MouseButtonEventArgs e)  
      {  
           MessageBox.Show("Mouse down handled in textblock");  
     }  
    

    In the above example if you mouse down on the Text Block, first the MouseDown event will be raised in the target Text Block then in Grid .

  2. Tunneling Event:

    This events are just opposite to Bubbling Events, the event first will be raised on the top most parent of the control on which the event is originally raised. From there, it will traverse to the target control like a tunneling.

     <Grid Name="mygrid" PreviewMouseDown="mygrid_PreviewMouseDown">  
         <TextBlock x:Name="textBox" PreviewMouseDown="textBox_PreviewMouseDown" HorizontalAlignment="Left" Height="23" TextWrapping="Wrap" Text="Bubbling event example" VerticalAlignment="Top" Width="120" Margin="193,154,0,0"/>  
      </Grid>  
    
     private void mygrid_PreviewMouseDown(object sender, MouseButtonEventArgs e)  
     {  
           MessageBox.Show("Preview Mouse Down handled in grid");  
     }  
     private void textBox_PreviewMouseDown(object sender, MouseButtonEventArgs e)  
     {  
           MessageBox.Show("Preview Mouse Down handled in textblock");  
     }  
    

    In the above example when you mouse down on the Text Block, first the PreviewMouseDown event will be raised in the Grid first then in the target Text Block. This type of event will be raised by Preview event, below are the list of most used Tunneling Events.

    • PreviewMouseDown
    • PreviewMouseUp
    • PreviewKeyUp
    • PreviewKeyDown

  3. Direct Event:

    WPF also supports Direct Event unlike classic WinForm, a routed event can be converted into direct event in WPF. When bubbling or tunneling is not required, then you may use e.Handled = true with in handler method to work Routed Event as Direct Event. This will stop the event from rising to the parent or child base on the event type.

Related Articles

  1. WPF Control Template
  2. WPF INotifyPropertyChanged Interface
  3. WPF Binding

Summary

In the above of this article, we have discussed the events are supported by WPF, hope this article may helpful to you.

Thanks

Comments

Popular posts from this blog

Generate QR Code in WPF

Introduction In my previous two blogs, we have discussed how to display generate and display various barcodes on the web page. In this blog, we are going to demonstrate how to Generate QR Code in the WPF application. Getting Started Here in the demonstration Generate QR Code in WPF , will generate QR code using third party library as there is not inbuilt library provided by Microsoft to generate QR code and will display in WPF image control, In the below, we will see the steps to display QR Code. As I mentioned in the above paragraph that there is no inbuild library provided by Microsoft to generate QR code, I have taken the help of the ZXing library which is a third party free library and available Nuget. This library provides various options to generate barcodes and QR Code from the user-friendly text. Generate QR Code in WPF Here are the steps to generate QR code and let's follow the steps to complete demonstrations. Demonstration:- Generate QR Code Open visual stud

Creating Application in Prism

Introduction This article explains an illustration of creating a windows application in Prism Library(WPF Prism). The solution includes recommended practices and techniques and is the basis for the procedures in Prism. This illustration created in the Visual Studio 2012, It can also developed in the visual studio 2008 and 2010, because wpf supports from .net framework 3.5 to latest version. Microsoft.Practices.Prism.dll. This assembly contains the implementation of the Prism Library core components such as modularity, logging services, communication services, and definitions for several core interfaces. It also contains the implementation of Prism Library components that target WPF applications, including commands, regions, and events. Microsoft.Practices.Prism.UnityExtensions.dll. This assembly contains base and utility classes you can reuse in applications built with the Prism Library that consume the Unity Application Block. For example, it contains a bootstrapper base class

WPF Binding

Introduction This blog describes WPF Binding and the measure elements exist with binding with XAML example in XAML and code-behind. Getting Started Binding helps in WPF to flow data from one object to another object, the object which fetches data is called source and the object which receives the data is called target. The Object a be a UI control or object of a class that means in binding you can bind a property of a class and property of another control to WPF UI controls as well. XAML Example <TextBox x:Name="sourceText" Grid.Row="0" /> <Button Grid.Row="1" Content="{Binding ElementName=sourceText, Path=Text}"/> Code Example Button btn=new Button(); Binding binding = new Binding("Text"); binding.Source = sourceText; btn.SetBinding(Button.ContentProperty, binding); In WPF binding has some measure properties or elements that we are using while developing application or projects, here we are going to d