2

I'm creating a custom control, and I'm having problems binding UI elements inside a DataTemplate to the custom control's dependency properties.

There's a content control in my control that should change its content and content template according to a certain property, so I bound it this way -

<ContentControl Content="{TemplateBinding ControlMode}" ContentTemplateSelector="{StaticResource TemplateSelector}"/>

The Content Template selector is defined this way -

<ns:TemplateSelector x:Key="TemplateSelector">
      <ns:TemplateSelector.Template1>
         <DataTemplate>
            <TreeView ItemsSource="{TemplateBinding TreeSource}"/>
         </DataTemplate>
      </ns:TemplateSelector.Template1>
      <ns:TemplateSelector.Template2>
          <DataTemplate>
              <ListView ItemsSource="{TemplateBinding ListSource}"/>
          </DataTemplate>
      </ns:TemplateSelector.Template2>
</ns:TemplateSelector>

The problem is that the TreeView and the ListView can't be bound to their itemssource with TemplateBinding due to this error for example -

"Cannot find TreeSourceProperty on the type ContentPresenter"

I've been looking around for an answer and I found this answer that simple states that this is impossible.

How to use template binding inside data template in custom control (Silverlight)

So if this really is impossible, how else could I bind the elements inside my template to the DependencyProperties of the CustomControl?

Thanks!

Community
  • 1
  • 1
Dror
  • 2,548
  • 4
  • 33
  • 51

1 Answers1

5

In WPF you can use a binding with RelativeSource targeting the "templated" control.

e.g.

{Binding TreeSource,
         RelativeSource={RelativeSource AncestorType=MyCustomControl}}

Edit: If you have a break in a tree you could possibly work around that by passing that control around, e.g.

<ControlThatOwnsPopup
    Tag="{Binding RelativeSource={RelativeSource AncestorType=MyCustomControl}}">
     <Popup>...
<TreeView ItemsSource="{Binding PlacementTarget.Tag.TreeSource,
                                RelativeSource={RelativeSource AncestorType=Popup}}"/>
H.B.
  • 166,899
  • 29
  • 327
  • 400
  • Yes this would work in a regular condition, but I forgot to mention that my CustomControl opens a popup (actually more of a window-popup), and this ContentControl actually resides in the popup, so finding the CustomControl in its ancestors will not work as it's not on the same logical tree. – Dror Feb 24 '12 at 07:53