Microsoft 9GD00001 Computer Accessories User Manual


 
Chapter 8: Building Desktop Applications with WPF 231
to user actions. In addition to creating the event handler in the code-behind, VS adds the
method name to the Click event on the Events tab in the Properties window, shown in
Figure 8-9.
In addition to creating the handler method and assigning the method name in the
Properties window, VS adds the method as an attribute to the Button control in the
XAML, shown here. The XAML is independent of programming language and works the
same regardless of whether you are coding in C# or VB:
<Button Content="Button" Height="23"
HorizontalAlignment="Left" Margin="76,43,0,0"
Name="button1" VerticalAlignment="Top" Width="75"
Click="button1_Click" />
Notice the convention being used on the method name, controlName_Event. The
controlName part comes from the name of the control, which is button1, and the event is
the event being handled. The problem with this is that button1 isn’t meaningful and when
you return to this code later, you’ll be confused by having methods named button1_Click,
button2_Click, and so on. To fix the naming problem, you should name your controls
properly before doing anything else with them.
To back out of this, go back to the Events tab of the Properties window. Remember to
select the Button in the Designer. The top left of the Properties window contains the ID of
the control, which you should change from button1 to a meaningful name. For example
if the purpose of the button was to create a new order for a customer, you could name the
button NewOrderButton. Then delete the event handler assigned to the Click event of the
Button. Figure 8-10 shows these changes in the Properties window. Now the ID and event
handler are more readable.
After the event handler is deleted and the control has a new ID, double-click the Click
event again. VS will create a new event handler for you, shown here:
C#:
private void button1_Click(object sender, RoutedEventArgs e)
{
}
private void NewOrderButton_Click(object sender, RoutedEventArgs e)
{
}