mjc*_*ple 4 wpf xaml hierarchicaldatatemplate
我有两个相同的 HierarchicalDataTemplates。唯一的区别是模板的数据类型。
<HierarchicalDataTemplate DataType="{x:Type Data:OuterType}"
ItemsSource="{Binding Items}">
<StackPanel>...</StackPanel>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate DataType="{x:Type Data:InnerType}"
ItemsSource="{Binding Items}">
<StackPanel>...</StackPanel>
</HierarchicalDataTemplate>
Run Code Online (Sandbox Code Playgroud)
如何避免在两个数据模板中复制堆栈面板的内容?
我考虑将 StackPanel 变成一个用户控件,但这是唯一可以使用该控件的地方。我宁愿 StackPanel 是某种资源,但我不知道如何使它工作。
我会去为那些看起来像这样的东西制作单独的模板:
<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>
Run Code Online (Sandbox Code Playgroud)
那里有架构上更优雅的解决方案,但外观和感觉是由设计师处理的,我不喜欢在这些事情上使用过于复杂的编程范式的解决方案。