#579 – Adding an Event Handler for a User Interface Element
June 13, 2012 Leave a comment
The simplest way to handle an event for a user interface element, like a Button or a Label, is to add a handler for the event to a single control.
Let’s say that we have some UI elements defined in XAML as follows.
<StackPanel Orientation="Vertical"> <Label Content="Some good movies:"/> <StackPanel Orientation="Horizontal" Margin="10"> <Label Content="Lawrence of Arabia" FontWeight="Bold"/> <Label Content="David Lean"/> <Button Content="Like" Padding="8,0"/> </StackPanel> <StackPanel Orientation="Horizontal" Margin="10"> <Label Content="Schindler's List" FontWeight="Bold"/> <Label Content="Steven Spielberg"/> <Button Content="Like" Padding="8,0"/> </StackPanel> </StackPanel>
You add a handler for a single UI element by specifying the name of the event and handler (method) in XAML.
<StackPanel Orientation="Horizontal" Margin="10"> <Label Content="Lawrence of Arabia" FontWeight="Bold"/> <Label Content="David Lean"/> <Button Content="Like" Padding="8,0" Click="btn_LawrenceLike"/> </StackPanel>
And then adding code for the handler in the code-behind file.
private void btn_LawrenceLike(object sender, RoutedEventArgs e) { MessageBox.Show("You like Lawrence of Arabia"); }