如何重用HierarchicalDataTemplate? [英] How do I reuse a HierarchicalDataTemplate?
问题描述
我有两个相同的HierarchicalDataTemplates.唯一的区别是模板的数据类型.
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?
我考虑过将StackPanel变成一个用户控件,但这是控件唯一可以使用的地方.我希望StackPanel是某种资源,但我不知道如何使它工作.
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.
推荐答案
我会为应该看起来像这样的东西制作单独的模板:
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.
这篇关于如何重用HierarchicalDataTemplate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!