简体   繁体   English

WPF 隧道按钮_Click

[英]WPF Tunneling a Button_Click

This is my first question so please go easy:)这是我的第一个问题,所以请 go 简单:)

I am new to WPF and Desktop based applications and I am studying Event Handling.我是 WPF 和基于桌面的应用程序的新手,我正在学习事件处理。 Going through Bubbling and Tunneling I can not find an example anywhere that explains how to use tunneling on a Button_Click.通过冒泡和隧道我在任何地方都找不到解释如何在 Button_Click 上使用隧道的示例。

Basically when I click a button I need the parent control (in this case a grid) to handle the event first and do some checks before allowing the Button_Click to take place.基本上,当我单击一个按钮时,我需要父控件(在本例中为网格)首先处理事件并在允许 Button_Click 发生之前进行一些检查。 The problem I am having is I can use the Grid_PreviewMouseDown to capture the event but this is ambiguous.我遇到的问题是我可以使用 Grid_PreviewMouseDown 来捕获事件,但这是不明确的。 It does not tell me (at least i think it doesnt) what control caused the handler to trigger.它没有告诉我(至少我认为它没有)是什么控制导致处理程序触发。

What can i do to determine the PreviewMouseDown was triggered by a Button Click?我该怎么做才能确定 PreviewMouseDown 是由按钮单击触发的? Or: Is there an alternative/better was to tunnel a Button_Click?或者:是否有替代/更好的方法是隧道 Button_Click?

Thanks谢谢

In your handler, you should inspect the Source of the event to get the control which initiated it.在您的处理程序中,您应该检查事件的Source以获取启动它的控件。 Just note that it is not readonly and could be changed so the Source refers to a different control.请注意,它不是只读的,可以更改,因此Source引用不同的控件。

You'll probably have better luck registering with the PreviewMouseLeftButtonDown event to get left clicks and not just any click.您可能会更幸运地注册PreviewMouseLeftButtonDown事件以获得左键单击,而不仅仅是任何单击。

If your handler is meant to only look for the left mouse click, you could use this code:如果您的处理程序仅用于查找鼠标左键单击,则可以使用以下代码:

private void Grid_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
    Button button = e.Source as Button;
    if (button != null)
    {
        // button is being clicked, handle it
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM