如何将 HierarchicalDataTemplate 中的 xaml 代码移动到资源

How to move xaml code inside HierarchicalDataTemplate to a resource

我有以下 TreeView 和几个 HierarchicalDataTemplates。在每个 HierarchicalDataTemplate 中,我都有一个 xaml 代码块来定义我的对象 X 的结构。

树视图示例

<TreeView ItemsSource="{Binding Cars}">
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type local:Car}"
                                  ItemsSource="{Binding Children}">
            <StackPanel>
                <TextBlock Text="{Binding Path=Name}"
                           FontSize="15" 
                           FontWeight="Medium"
                           Foreground="Brown"/>
            </StackPanel>
        </HierarchicalDataTemplate>
</TreeView>

现在我想将 StackPanel 移动到资源 e.x。在 UserControl 资源中。
我尝试定义一个 DataTemplate 并将其用作 HierarchicalDataTemplate 的 ItemTemplate,但这不起作用。

我的尝试:

<DataTemplate x:Key="ModuleTemplate"
              DataType="{x:Type local:Module}">
    <StackPanel>
        <TextBlock Text="{Binding Path=Name}"
                   FontSize="15" 
                   FontWeight="Medium"
                   Foreground="Brown"/>
    </StackPanel>
</DataTemplate>

<!-- TreeView section-->
<HierarchicalDataTemplate DataType="{x:Type local:Car}"
                          ItemsSource="{Binding Children}"
                          ItemTemplate="{StaticResource ModuleTemplate}">

@mm8 的想法很好并且可行,但在我的情况下会导致很多 UserControls。我宁愿选择更简单的东西。

有什么办法可以实现我的目标吗?

Now I would like to move the StackPanel to a resource, e.x. inside UserControl resource.

试试这个:

<HierarchicalDataTemplate DataType="{x:Type local:Car}"
                          ItemsSource="{Binding Children}">
        <local:UserControl1 />
</HierarchicalDataTemplate>

...其中 UserControl1 是一个 UserControl,里面有 StackPanel

<UserControl...>
    <StackPanel>...</StackPanel>
</UserControl>

I still just want to move the code inside (the) HierarchicalDataTemplate to UserControl.Resources ...

然后使用 x:Shared attribute:

StackPanel 定义为非共享资源
<UserControl.Resources>
    <StackPanel x:Key="sp" x:Shared="False">
        <TextBlock Text="{Binding Path=Name}"
                   FontSize="15" 
                   FontWeight="Medium"
                   Foreground="Brown"/>
    </StackPanel>

    <HierarchicalDataTemplate DataType="{x:Type local:Car}"
                              ItemsSource="{Binding Children}">
        <ContentControl Content="{StaticResource sp}" />
    </HierarchicalDataTemplate>
</UserControl.Resources>