Can't find the parent of a templated control by type(!) (wpf)

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


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) ....


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

Need Your Help

How do I add a UIview to an imageView while ensuring that the contents of the UIView are inside the it's frame?

ios swift uiview ios8 addsubview

I have a superview which contains a ImageView, a testView, and some buttons. I created a UIView which contains ImageView2 and a removebutton.

Android: Using onPause() Selectively

java android onpause

I have a single activity timer application in which I have overridden the onPause() method to pause the timer when the user presses the home or back button. However, I would like the timer to keep ...

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.