Question

I have two identical HierarchicalDataTemplates. The only difference is the DataType of the templates.

<HierarchicalDataTemplate DataType="{x:Type Data:OuterType}"
                          ItemsSource="{Binding Items}">
    <StackPanel>...</StackPanel>
</HierarchicalDataTemplate>

<HierarchicalDataTemplate DataType="{x:Type Data:InnerType}"
                          ItemsSource="{Binding Items}">
    <StackPanel>...</StackPanel>
</HierarchicalDataTemplate>

How can I avoid duplicating the contents of the stack panel in both data templates?

I considered making the StackPanel into a user control, but this is the only place that control would ever be used. I would rather the StackPanel be some kind of resource, but I can't figure out how to make that work.

Was it helpful?

Solution

I would go the route of making seperate templates for things that are supposed to look the same like this:

<DataTemplate x:Key="sharedTemplate">
    <StackPanel>...</StackPanel>
</DataTemplate>

<HierarchicalDataTemplate DataType="{x:Type InnerType}"
                            ItemsSource="{Binding Items}">
    <ContentControl Content="{Binding}"
                    ContentTemplate="{StaticResource sharedTemplate}" />
</HierarchicalDataTemplate>

<HierarchicalDataTemplate DataType="{x:Type OuterType}"
                            ItemsSource="{Binding Items}">
    <ContentControl Content="{Binding}"
                    ContentTemplate="{StaticResource sharedTemplate}" />
</HierarchicalDataTemplate>

There are architecturally more elegant solutions out there, but seeing look and feel is handled by designers I don't like to use solutions that are too complex programming paradigm wise in these things.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top