Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I use a DataTemplateSelector within a DataTemplate?

I have an ItemsControl using a StackPanel to display a list of items.

I would like a label to appear for each row, but for the content to the left of the label to be defined by a DataTemplateSelector. I do not want to redefine the label for each DataTemplate generated by the TemplateSelector.

Is this possible?

<ItemsControl ItemsSource="{Binding Path=Values}" >
 <ItemsControl.Resources>
   <v:MyTemplateSelector x:Key="myTemplateSelector"></v:MyTemplateSelector>
 </ItemsControl.Resources>
 <ItemsControl.ItemsPanel>
  <ItemsPanelTemplate>
   <StackPanel></StackPanel>
  </ItemsPanelTemplate>
 </ItemsControl.ItemsPanel>
 <ItemsControl.ItemTemplate>
  <DataTemplate>
   <WrapPanel>
    <Label>Test: </Label>
    <!--What goes here should be defined by myTemplateSelector-->
   </WrapPanel>
  </DataTemplate>
 </ItemsControl.ItemTemplate>
</ItemsControl>
like image 416
Greg Sansom Avatar asked Dec 31 '10 03:12

Greg Sansom


1 Answers

I figured it out. The solution was to use a ContentPresenter element with a ContentTemplateSelector attribute:

    <DataTemplate>
       <WrapPanel>
          <Label>Test: </Label>
          <ContentPresenter 
              ContentTemplateSelector="{StaticResource ResourceKey=myTemplateSelector}">
          </ContentPresenter>
       </WrapPanel>
    </DataTemplate>
like image 200
Greg Sansom Avatar answered Oct 09 '22 14:10

Greg Sansom