Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

wpf

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

like image 672
Xavier Huppé Avatar asked Feb 27 '14 20:02

Xavier Huppé


People also ask

What is the difference between grid and DataGrid in WPF?

A Grid is a control for laying out other controls on the form (or page). A DataGrid is a control for displaying tabular data as read from a database for example.

What is the difference between grid and StackPanel in WPF?

The difference is the way they contain elements. Elements in Grid are stored in matrix form or you can say tabular form. You can define columndefinitions and rowdefinitions and you can access and store element at a particular row and column. But in stackpanel, elements are stored in stack format .

How do I show grid lines in WPF?

First Method: By typing XAML Code ColumnDefinitions property. By default, GridLines are invisible. For showing the GridLines, set the ShowGridLines property of the Grid to True.

What are the child elements of a grid called?

The following example defines a parent Grid element ( grid1 ) that has three columns and three rows. A child Rectangle element ( rect1 ) is added to the Grid in column position zero, row position zero. Button elements represent methods that can be called to reposition the Rectangle element within the Grid.


1 Answers

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.

like image 124
Sheridan Avatar answered Nov 19 '22 20:11

Sheridan