WPF Basics - Event Handling

Events are used to implement a publish/subscribe model (aka an Observer pattern). Event handling in WPF is very similar to that of Winforms. A control declares a number of events that it can raise in response to activity either by the user or by the system. The most simple example is a button exposing a click event, or a textbox exposing a textchanged event.

Subscribing to Events

Hooking up events via XAML is as simple as using an attribute. An element has a corresponding attribute for each of its events. The value of the attribute is the name of the method in the code file that will handle the event. An exception
<Button Name="button1" Click="button1_Click">Submit</Button> <TextBox Name="textBox1" TextChanged="textBox1_TextChanged" /> <Slider Name="slider1" ValueChanged="slider1_ValueChanged" />
Subscribing to events can also be done via code using standard .NET syntax. For example, the following is equivalent to the XAML code above used for a button, textbox, and a slider. The type of handler depends on the event definition.
button1.Click+=new RoutedEventHandler(button1_Click); textBox1.TextChanged+=new TextChangedEventHandler(textBox1_TextChanged); slider1.ValueChanged+=new RoutedPropertyChangedEventHandler<double>(slider1_ValueChanged);
Whether you subscribe to events via code or via XAML, the methods to handle the events will be the same. To complete the example above, here are three method definitions that will be called when the events are raised by the appropriate controls.
private void button1_Click(object sender, RoutedEventArgs e) { textBlock1.Text = "Button Clicked"; } private void textBox1_TextChanged(object sender, TextChangedEventArgs e) { textBlock1.Text = "Textbox Text Changed"; } private void slider1_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e) { textBlock1.Text = "Slider Value Changed"; }
Copyright 2008 - www.WPFDude.com