WPF 隧道 Button_Click

发布于 2024-11-29 07:37:36 字数 347 浏览 5 评论 0原文

这是我的第一个问题,所以请简单点:)

我是 WPF 和基于桌面的应用程序的新手,我正在研究事件处理。通过冒泡和隧道,我无法在任何地方找到解释如何在 Button_Click 上使用隧道的示例。

基本上,当我单击按钮时,我需要父控件(在本例中为网格)首先处理该事件,并在允许 Button_Click 发生之前进行一些检查。我遇到的问题是我可以使用 Grid_PreviewMouseDown 来捕获事件,但这不明确!它没有告诉我(至少我认为它没有)是什么控制导致处理程序触发。

我该如何确定 PreviewMouseDown 是由按钮单击触发的?或者: 是否有替代/更好的方法是隧道 Button_Click?

谢谢

This is my first question so please go easy :)

I am new to WPF and Desktop based applications and I am studying Event Handling. Going through Bubbling and Tunneling I can not find an example anywhere that explains how to use tunneling on a 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. The problem I am having is I can use the Grid_PreviewMouseDown to capture the event but this is ambiguous! 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? Or:
Is there an alternative/better was to tunnel a Button_Click?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

开始看清了 2024-12-06 07:37:36

在您的处理程序中,您应该检查 Source< /code>事件以获取启动它的控件。请注意,它不是只读的,可以更改,因此 Source 引用不同的控件。

您可能会更幸运地注册 PreviewMouseLeftButtonDown 事件来获取左键单击,而不仅仅是任何单击。

如果您的处理程序只想查找鼠标左键单击,则可以使用以下代码:

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

In your handler, you should inspect the Source of the event to get the control which initiated it. Just note that it is not readonly and could be changed so the Source refers to a different control.

You'll probably have better luck registering with the PreviewMouseLeftButtonDown event to get left clicks and not just any click.

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
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文