#607 – An Instance Handler vs. A Class Handler

In WPF, when you define an event handler, the event handler is typically an instance handler–i.e. an event handler associated with a specific instance of a control.  In the XAML below, we’ve defined an event handler for one particular Button.

<Button Content="Like" Click="btnLike_Click"/>

You can also define a class handler–an event handler that is associated with all instances of a particular type, rather than one instance.  It will be called whenever the event in question passes through any instance of the specified type.

For example, we can define a handler that will be called when the user clicks on any Button control.

        public MainWindow()

            // Call when user clicks on any Button
                new RoutedEventHandler(HandleAllButtons));

        private void HandleAllButtons(object sender, RoutedEventArgs e)
            Button b = (Button)e.Source;
            Trace.WriteLine(string.Format("* You clicked on [{0}] button", b.Content));