Search This Blog

Thursday, November 14, 2013

Routed event WPF

WPF > routed event

A routed event can invoke handlers on multiple listeners in an element tree.

Example

<Window x:Class="WpfApplication1.Window1"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Window1" Height="300" Width="300">
    <Grid>
        <Border Height="50"  BorderBrush="White" BorderThickness="1">
            <StackPanel Orientation="Horizontal" Button.Click="CommonClickHandler">
                <Button Name="Button" Click="Button_Click">Button</Button>
                <CheckBox x:Name="CheckBox" />
            </StackPanel>
        </Border>
    </Grid>
</Window>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace WpfApplication1
{

    /// <summary>
    /// Interaction logic for Window1.xaml
    /// </summary>

    public partial class Window1 : Window
    {
        public Window1()
        {
            InitializeComponent();
        }
        private void CommonClickHandler(object sender, RoutedEventArgs e)
        {
            FrameworkElement feSource = e.Source as FrameworkElement;
            switch (feSource.Name)
            {
                case "Button":
                    MessageBox.Show("Event fired on Button"); 
                    break;
                case "CheckBox":
                    MessageBox.Show("Event fired on CheckBox"); 
                    break;
            }
            e.Handled = true;
        }
    }
}