问题
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.
回答1:
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.
来源:https://stackoverflow.com/questions/17884643/how-do-i-reuse-a-hierarchicaldatatemplate