Search code examples
wpfxamldatatemplatecontentpresenter

Reusing DataTemplates


With a few GroupBoxes in my UI, I'm modifying their HeaderTemplate to add icons in addition to the text caption. Here's my template:

<DataTemplate>
  <Grid>
    <Grid.ColumnDefinitions>
      <ColumnDefinition Width="Auto" />
      <ColumnDefinition Width="*" />
    </Grid.ColumnDefinitions>
    <Image Source="/Resources/IDCard.png" />
    <TextBlock Grid.Column="1" Text="{Binding}" VerticalAlignment="Center" />
  </Grid>
</DataTemplate>

This works, however since I have got multiple GroupBoxes, I was thinking of a way to define this template in Window's Resources and then reference it in each GroupBox. How can I use ContentPresenter (or anything else for that matter) in place of <Image> control in the above template and then provide the actual content (icon) in each GroupBox separately?

Note: I'm looking for XAML-only solution.


Solution

  • You could try to use DynamicResource lookup (along the lines of this example).