UserControl 两次将点击事件传递给 MainWindow

UserControl passes click event to MainWindow Twice

我终于让我的 UserControl 完成我需要的一切,生成一个带有图标和文本的按钮,但是当我尝试将点击事件传递到我的 Main Window 时,我发现它触发了两次!在下面的缩写代码中,我的测试 MessageBox 出现两次以响应一次单击。也就是说,它出现一次。我单击“确定”,它第二次出现。在我第二次单击“确定”后,它继续。感谢您查看此内容。

<UserControl x:Class=ImageButton"
....
<Button Style="{DynamicResource ImageButtonStyle}" Click="uc_Click"/>
</UserControl>
----
Public Class ImageButton
Public Event Click as RoutedEventHandler
....
Private Sub uc_Click(sender as Object, e As RoutedEventArgs)
    RaiseEvent Click(Me, e)
End Sub
End Class
----
<Window x:Class="MainWindow"
....
<local:ImageButton x:Name=NewItem" Click="NI_Click"></local:ImageButton>
----
Class MainWindow
....
 Private Sub NI_Click(sender As Object, e As RoutedEventArgs) Handles NewItem.Click
    MessageBox.Show("Success")
End Sub
End Class

您在 XAML 和代码隐藏中添加了两个事件处理程序。

只需从 MainWindow class 后面的代码中删除 Handles NewItem.Click

Private Sub NI_Click(sender As Object, e As RoutedEventArgs)
    MessageBox.Show("Success")
End Sub

从视图中删除Click="NI_Click"

...
<local:ImageButton x:Name="NewItem"></local:ImageButton>
...