Aaron Summernite
Aaron Summernite

Reputation: 365

Handling event's doesn't work from code in WPF

I am working on a project and I have encountered problem I can't seem to resolve myself. I have simplified code as much as possible and started a new small project to see if this is not caused by any interference with the rest of bigger project.

This is what I have got:

XAML:

<Window Loaded="Window_Loaded" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="MainWindow">
<Label MouseDown="Label1_MouseDown" Content="y u no work?!" Name="Label1"/>
</Window>

CODE:

Class MainWindow 

Private Sub Label1_MouseDown(sender As System.Object, e As System.Windows.Input.MouseButtonEventArgs)
    MsgBox("md1")
End Sub

Private Sub Window_Loaded(sender As System.Object, e As System.Windows.RoutedEventArgs)
    ' Doesn't work
    Label1.AddHandler(Mouse.MouseDownEvent, Sub() MsgBox("md2"))
    ' Doesn't work neither
    Mouse.AddMouseDownHandler(Label1, Sub() MsgBox("md3"))
End Sub

End Class

"md1" pops up, as expected. "md2" and "md3" doesn't. Where do you think I made a mistake?

Upvotes: 2

Views: 1189

Answers (1)

SeriousSamP
SeriousSamP

Reputation: 436

The following line is wrong and throws a silent "Handler type is mismatched" exception.

Label1.AddHandler(Mouse.MouseDownEvent, Sub() MsgBox("md2"))

As a result, the next line that is actually perfectly good does not run.

So the following works fine.

Private Sub Window_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs)
    Mouse.AddMouseDownHandler(Label1, Sub() MsgBox("md2"))
    Mouse.AddMouseDownHandler(Label1, Sub() MsgBox("md3"))
End Sub

I personally would have used the following to add the handlers but I am not sure if there is any advantage or difference other than, in my opinion, improved readability.

AddHandler Label1.MouseDown, Sub() MsgBox("md4")

I hope this is helpful,
Sam.

Upvotes: 3

Related Questions