2017-02-04 74 views
1

事件不工作我正在使用的Windows Presentation Foundation(WPF)的GUI。当我点击一个按钮(左或右)时,我想显示一个消息框。到目前为止我已经成功地从教程中做出了一个例子,但它只在我的右键点击而不是的时候点击了我的左键点击了这个按钮。我在代码中看不到任何东西,这可以防止左键单击工作,所以我希望你能帮助我。的MouseUp左键单击

XAML代码

<Grid> 
    <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="72"> 
     Hello, WPF! 
    </TextBlock> 

    <!-- This button shuld activate the even MyButton_MouseUp --> 
    <Button Margin="200,250,200,20" Name="MyButton" MouseUp="MyButton_MouseUp"> 
     Test 
    </Button> 
</Grid> 

C#代码

// This only works on right-click 
private void MyButton_MouseUp(object sender, MouseButtonEventArgs e) 
{ 
    MessageBox.Show("Hello world!"); 
} 

回答

2

您可以订阅PreviewMouseUp隧道化事件而不是MouseUp

<Button Margin="200,250,200,20" Name="MyButton" PreviewMouseUp="MyButton_MouseUp" /> 

PreviewMouseUp路由策略隧道,即它会去VisualTree层次的下降,所以Tunnel events是在Bubble events之前触发。

+0

谢谢,那就是诀窍。你还可以解释为什么吗? :-) – Noceo

+1

@Noceo见我的更新答案,也看看我包括MSDN链接。 –

+0

很酷。尽管如此,我仍然没有明白为什么它能够右键点击,但至少现在我知道有不同的事件类型。再次感谢。 – Noceo

相关问题