How do I reuse a HierarchicalDataTemplate?

心不动则不痛 提交于 2020-01-13 05:49:32

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!