Search code examples
wpftemplateswpf-controlsparentonmouseclick

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


Solution

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