41

I'm trying to understand RelativeSource binding but I can't find a definition for TemplatedParent. MSDN says:

"Gets a static value that is used to return a RelativeSource constructed for the TemplatedParent mode."

It doesn't appear in the index of "Windows Presentation Foundation Unleashed".

Simply, what is a TemplatedParent please?

David Smith
  • 892
  • 1
  • 6
  • 16

3 Answers3

44

TemplatedParent refers to the Control instance that the template is being applied to. You can use TemplatedParent to bind to properties declared on that object (and its base classes).

Gabe
  • 84,912
  • 12
  • 139
  • 238
  • 6
    So if I had a TextBox inside a StackPanel inside a DataTemplate of an ItemsControl, the TemplatedParent of the TextBox would be the ItemsControl not the StackPanel? – David Smith Mar 14 '11 at 05:28
  • 2
    @David: The `TemplatedParent` for an item in an `ItemsControl` is neither of the ones you think. I believe it's a `ContentPresenter` instance (a separate one for each item in your `ItemsSource`). – Gabe Mar 14 '11 at 05:43
  • Hmm, thanks Gabe, but I think I'm lost again. ConentPresenter is not in the index of "WPF Unleashed", I'll have to do some more searching... – David Smith Mar 14 '11 at 06:02
  • 5
    @David: See http://msdn.microsoft.com/en-us/library/system.windows.controls.contentpresenter.aspx for all the gory details. – Gabe Mar 14 '11 at 06:07
  • Hi, thanks for this explanation. I was just wondering if there's a difference with {RelativeSource Self} ? – PlaTyPuS Nov 17 '16 at 09:52
8

In WPF, a template is what it uses to construct the tree of a type. WPF essentially makes a copy of the template when a new object of that type is created.

As a result, inside the template, if you want to refer to the new object, you use TemplatedParent for quick access. Otherwise, you'll have to use RelativeSource to walk the tree upwards to find the parent object.

Stephen Chung
  • 14,497
  • 1
  • 35
  • 48
0

Notice:

TemplatedParent means Parent is Templated. Templated is passive voice in English. In other words, the parent element is applied with a Template. So in the template you can binding the parent's property easily.

Bigeyes
  • 1,508
  • 2
  • 23
  • 42