#607 – An Instance Handler vs. A Class Handler
July 20, 2012 1 Comment
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() { this.InitializeComponent(); // Call when user clicks on any Button EventManager.RegisterClassHandler( typeof(Button), ButtonBase.ClickEvent, 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)); }