Prev | Current Page 315 | Next

Matthew MacDonald

"Pro WPF with VB 2008: Windows Presentation Foundation with .NET 3.5"

If you attach an event handler
to Button.Click, it??™s only used for Button objects.
You can wire up an attached event in code, but you need to use the UIElement.Add-
Handler() method rather than the AddHandler() statement that??™s part of the Visual Basic
language. Here??™s an example (which assumes the StackPanel has been given the name
pnlButtons):
pnlButtons.AddHandler(Button.Click, New RoutedEventHandler(DoSomething))
In the DoSomething() event handler you have several options for determining which button
fired the event. You can compare its text (which will cause problems for localization) or its
name (which is fragile because you won??™t catch mistyped names when you build the application).
The best approach is to make sure each button has a Name property set in XAML, so
that you can access the corresponding object through a field in your window class and compare
that reference with the event sender. Here??™s an example:
Private Sub DoSomething(ByVal sender As Object, ByVal e As RoutedEventArgs)
If sender Is cmd1 Then
...
ElseIf sender Is cmd2 Then
...
ElseIf sender Is cmd3 Then
...
End If
End Sub
Another option is to simply send a piece of information along with the button that you
can use in your code. For example, you could set the Tag property of each button, as shown
here: