Xavier Huppé
Xavier Huppé

Reputation: 544

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

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

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.

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

Thanks in advance

Upvotes: 9

Views: 22043

Answers (2)

Sheridan
Sheridan

Reputation: 69985

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.PreviewMouseDown event. Try this:

<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.MouseDown event wouldn't work with Buttons for that very reason. However, you can use the othwer Preview... methods, like the UIElement.PreviewLeftMouseButtonDown event, for example.

Upvotes: 16

Siti
Siti

Reputation: 130

Can you give your sample code?

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

.xaml

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

.xaml.cs

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

edit: How about this?

Upvotes: 3

Related Questions