Wpf – Bind DataTemplate to CustomControl problem

custom-controlsdata-bindingdatatemplatesilverlightwpf

What I've got is a custom control, which implements datatemplate in xaml:

<DataTemplate x:Key="Templat">
    <StackPanel>
        <TextBlock Text="Sample Text" />
        <TextBlock Text="{Binding Surname}" />
    </StackPanel>
</DataTemplate>

and custom control:

 <local:MyControl x:Name="MyControl1" 
      ItemTemplate="{StaticResource Templat}" Margin="0,0,-24,8"/>

generic.xaml (in my custom control library) has:

<ControlTemplate TargetType="local:MyControl">
   <Canvas Name="LayoutRoot" Height="{TemplateBinding Height}" 
           Width="{TemplateBinding Width}" 
           Background="{TemplateBinding Background}" 
           CacheMode="BitmapCache">

      <Canvas Name="ItemsHost" Margin="10,185,0,0" Height="615" 
              Width="{TemplateBinding Width}" CacheMode="BitmapCache">
           <local:CustomItem x:Name="Item1" 
                  ContentTemplate="{TemplateBinding ItemTemplate}" />
           <local:CustomItem x:Name="Item2" 
                  ContentTemplate="{TemplateBinding ItemTemplate}" />
      </Canvas>  
   </Canvas> 
</ControlTemplate> 

What am I doing wrong?

I created a custom item control, which has a few custom content controls inside. I want them all to have the same content template, so I bound their content template to defined itemtemplate in parent control.

My problem is that controls will show textblock with "Sample Text" text, but not the one with the binded value. I was trying to specify DataContext in codebehind (like DataContext = new Person() { Surname="Johnson" } or via xaml. None of them worked.

The DataContext (Person class) looks like was passed correct, but passed DataTemplate misses the '{Binding Surname}' expression. Have you got any ideas what can be wrong?

Best Answer

The DataContext of the controls in the DataTemplate is not inherited from it's parent. So in your case, everything in the Templat will have a different DataContext than CustomItem and MyControl.

The DataContext for the DataTemplate comes from the Content property of the associated ContentControl or ContentPresenter. So in your case, if you did this:

<local:CustomItem x:Name="Item1" Content="{Binding}" ContentTemplate="{TemplateBinding ItemTemplate}" />

Then you could set the DataContext of MyControl, and it would get passed down to your DataTemplate.

From the looks of it though, your MyControl should be an ItemsControl though (as explained here).

Related Topic