6

In my WPF project I have a bit complex control. In the project I only use Controls (they're all templated), besides MainWindow.

On one screen I have the following layout (for showing the layout after templates have been applied and contents filled):

MyScreenControl
-MyTableControl
--ItemsControl
--- HeaderItemsControl
-----HeaderItemsControl.Header
------MyHeaderControl
-----HeaderItemsControl.Items
------MyItemControl
------MyItemControl
------MyItemControl
...

When I'm in the ScreenControl's code file, in the OnMouseLeftButtonDown method I would like to determine if the click event came from a MyHeaderControl or a MyItemControl.

The MouseButtonEventArgs's Source is the ScreenControl and the OriginalSource is the TextBlock in the MyItemControl/MyHeaderControl 's template.

My first attempt to find the MyItemControl/MyHeaderControl was to start from the OriginalSource and recursively look at the type of the Parent property. It works fine till I get to the root of the Template (which is in this case a ViewBox), but the root has no Parent element.

I've used a method like this in az earlier project of mine and it worked, but then I was working with UserControls, not Controls, nor Templates.

Any ideas how should I approach this problem (a good idea is as wellcome as a code)?

thx, Tenshiko

Tenshiko
  • 1,450
  • 3
  • 17
  • 33
  • Sometimes it can be helpful to look for the parent, not until the child has been loaded. For example, you can use the yourChild.Loaded event – peter70 May 11 '17 at 07:36

2 Answers2

7

Have you tried simply to get the originalSource's templatedParent ? :

Control originalSource = e.OriginalSource;

MyItemControl myItemControl = originalSource.TemplatedParent as MyItemControl;
MyHeaderControl myHeaderControl = originalSource.TemplatedParent as MyHeaderControl;

if (MyItemControl != null) ....
else if (MyHeaderControl != null) ....

(see: http://msdn.microsoft.com/en-gb/library/system.windows.frameworkelement.templatedparent.aspx)

David
  • 6,014
  • 4
  • 39
  • 55
4

Check out VisualTreeHelper.GetParent, which will let you walk the visual tree where the controls have actually been instantiated through the template.

Dan Bryant
  • 27,329
  • 4
  • 56
  • 102