Search code examples
wpfxamltreeviewdatatemplatehierarchicaldatatemplate

How to move xaml code inside HierarchicalDataTemplate to a resource


I have the following TreeView with several HierarchicalDataTemplates. Inside every HierarchicalDataTemplate I have a block of xaml code to define the structure of my object X.

TreeView Example

<TreeView ItemsSource="{Binding Cars}">
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type local:Car}"
                                  ItemsSource="{Binding Children}">
            <StackPanel>
                <TextBlock Text="{Binding Path=Name}"
                           FontSize="15" 
                           FontWeight="Medium"
                           Foreground="Brown"/>
            </StackPanel>
        </HierarchicalDataTemplate>
</TreeView>

Now I would like to move the StackPanel to a resource, e.x. inside UserControl resource.
I tried defining a DataTemplate and using it as ItemTemplate for the HierarchicalDataTemplate but this does not work.

My attempt:

<DataTemplate x:Key="ModuleTemplate"
              DataType="{x:Type local:Module}">
    <StackPanel>
        <TextBlock Text="{Binding Path=Name}"
                   FontSize="15" 
                   FontWeight="Medium"
                   Foreground="Brown"/>
    </StackPanel>
</DataTemplate>

<!-- TreeView section-->
<HierarchicalDataTemplate DataType="{x:Type local:Car}"
                          ItemsSource="{Binding Children}"
                          ItemTemplate="{StaticResource ModuleTemplate}">

The idea from @mm8 is fine and would work, but in my case that would lead to many UserControls. I Would rather prefer something simpler.

Any ideas how can I achieve my goal?


Solution

  • I still just want to move the code inside (the) HierarchicalDataTemplate to UserControl.Resources ...

    Then define the StackPanel as non-shared resource using the x:Shared attribute:

    <UserControl.Resources>
        <StackPanel x:Key="sp" x:Shared="False">
            <TextBlock Text="{Binding Path=Name}"
                       FontSize="15" 
                       FontWeight="Medium"
                       Foreground="Brown"/>
        </StackPanel>
    
        <HierarchicalDataTemplate DataType="{x:Type local:Car}"
                                  ItemsSource="{Binding Children}">
            <ContentControl Content="{StaticResource sp}" />
        </HierarchicalDataTemplate>
    </UserControl.Resources>