WPF 捕捉单击网格及其所有子标签、文本框等。

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22080083/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 11:02:34  来源:igfitidea点击:

WPF catch Click on a grid and all of his children labels, textboxs, etc.

c#wpf

提问by Xavier Huppé

Lets say I have a xaml file, a window, why not. in this xaml I have a gridwith multiple labels, textBoxs, comboBoxs, lists... You see the patern. At a certain point (where X == true for say) I want to be able to catcha click inside the grid and everything in it.

假设我有一个 xaml 文件,一个窗口,为什么不呢。在这个 xaml 中,我有一个带有多个标签、文本框、组合框、列表的网格......你看到了模式。在某个时刻(例如 X == true),我希望能够捕捉到网格内部及其中的所有内容的点击

I want to be still able to do what this click was going to do so a full-filled Rect over the grid is not the answer I'm looking for. The action of the click would be to put X back to false. nothing much.

我希望仍然能够做这次点击要做的事情,所以网格上的全填充 Rect 不是我正在寻找的答案。单击的操作是将 X 重新设置为 false。没什么。

Is there an easy way to manage a click on a grid and everything inside it?

有没有一种简单的方法来管理对网格及其内部所有内容的点击?

Thanks in advance

提前致谢

回答by Sheridan

You just need to use an event that is common to all of the controls. Probably the best one for this scenario is the UIElement.PreviewMouseDownevent. Try this:

您只需要使用所有控件通用的事件。可能最适合这种情况的是UIElement.PreviewMouseDownevent。尝试这个:

<StackPanel UIElement.PreviewMouseDown="StackPanel_PreviewMouseDown">
    <Label Content="I'm a Label" />
    <Button Content="I'm a Button" />
    <CheckBox Content="I'm a CheckBox" />
</StackPanel>

You need to use one of the Preview...events so that you can catch it before the Buttons consume it... the UIElement.MouseDownevent wouldn't work with Buttons for that very reason. However, you can use the othwer Preview...methods, like the UIElement.PreviewLeftMouseButtonDownevent, for example.

您需要使用其中一个Preview...事件,以便您可以在Buttons 消耗它之前捕获它……正是出于这个原因,该UIElement.MouseDown事件无法与Buttons 一起使用。但是,您可以使用其他Preview...方法,例如UIElement.PreviewLeftMouseButtonDown事件。

回答by Lyra___

Can you give your sample code?

你能给出你的示例代码吗?

From my understanding,you can use this,it will capture all your click inside grid.

根据我的理解,您可以使用它,它将捕获您在网格内的所有点击。

.xaml

.xaml

<Grid MouseDown="Grid_MouseDown">
<Label MouseDown="Grid_MouseDown" />
<Button MouseDown="Grid_MouseDown"/>
<Button MouseDown="Grid_MouseDown"/>
</Grid>

.xaml.cs

.xaml.cs

private Grid_MouseDown(object sender,MouseButtonEventArgs e)
{
    if(X==true)
    {
      //doSomething
    }
    else
    {
     //do SomethingElse
    }
}

edit: How about this?

编辑:这个怎么样?