Cannot find parent of template control (!) (Wpf)

In my WPF project, I have a little complicated control. In the project, I use only controls (they are all templates), except for MainWindow.

On one screen, I have the following layout (to display the layout after applying the templates and filling the contents):

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

When I get into the ScreenControl code file, in the OnMouseLeftButtonDown method, I would like to determine if the click event from MyHeaderControl or MyItemControl has occurred.

The MouseButtonEventArgs source is a ScreenControl, and the source source is a TextBlock in the MyItemControl / MyHeaderControl template.

My first attempt to find MyItemControl / MyHeaderControl was to start with a SourceSource and look at the type of the Parent property recursively. It works fine until I get to the root of the template (which is the ViewBox in this case), but the root does not have a parent element.

I used a method similar to this in myz previous project, and it worked, but then I worked with UserControls and not with Controls or Templates.

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

THX, Tenshiko

+4
source share
2 answers

Have you tried just getting the original templatedParent template?

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 )

+4
source

Check out VisualTreeHelper.GetParent , which will allow you to traverse the visual tree where the controls were actually created through the template.

+2
source

All Articles