Routed Events in WPF

XAML Code: 

  1. <Window x:Class="LearningWPF.MainWindow"  
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.   
  5.     Title="MainWindow" Height="350" Width="525" Background="Azure">  
  6.     <Grid x:Name="grdMain" Height="100" Width="500" HorizontalAlignment="Center"         VerticalAlignment="Center" IsHitTestVisible="True" Background="Black" ToolTip="Grid">  
  7.         <Grid.RowDefinitions></Grid.RowDefinitions>  
  8.         <StackPanel x:Name="stkMain" Grid.Row="0" Height="80" Width="250"                   IsHitTestVisible="True" Background="Yellow" ToolTip="StackPanel">  
  9.             <Button x:Name="btnClick" Content="Click Me" Height="50" Width="90"             Background="Pink" Margin="10" ToolTip="Click Button" IsHitTestVisible="True"/>  
  10.         </StackPanel>  
  11.     </Grid>  
  12. </Window>  
Code behind file: 
  1. using System.Windows;  
  2. using System.Windows.Input;  
  3. namespace LearningWPF {  
  4.     public partial class MainWindow: Window {  
  5.         public MainWindow() {  
  6.             InitializeComponent();  
  7.             grdMain.MouseDown += Grid_MouseDown;  
  8.             stkMain.MouseDown += StackPanel_MouseDown;  
  9.             btnClick.MouseDown += btnClick_MouseDown;  
  10.         }  
  11.         void btnClick_Click(object sender, RoutedEventArgs e) {  
  12.             MessageBox.Show("Direct Event is getting fired");  
  13.         }  
  14.         private void btnClick_MouseDown(object sender, MouseButtonEventArgs e) {  
  15.             MessageBox.Show("Button MouseDown Called");  
  16.         }  
  17.         private void StackPanel_MouseDown(object sender, MouseButtonEventArgs e) {  
  18.             MessageBox.Show("StackPanel MouseDown Called");  
  19.         }  
  20.         private void Grid_MouseDown(object sender, MouseButtonEventArgs e) {  
  21.             MessageBox.Show("Grid MouseDown Called");  
  22.         }  
  23.         private void Grid_PreviewMouseDown(object sender, MouseButtonEventArgs e) {  
  24.             MessageBox.Show("Grid Preview MouseDown Called");  
  25.         }  
  26.         private void StackPanel_PreviewMouseDown(object sender, MouseButtonEventArgs e) {  
  27.             MessageBox.Show("StackPanel Preview MouseDown Called");  
  28.         }  
  29.         private void btnClick_PreviewMouseDown(object sender, MouseButtonEventArgs e) {  
  30.             MessageBox.Show("Button Preview MouseDown Called");  
  31.         }  
  32.     }  
  33. }