单个 xaml 中具有相同绑定的多个控件

Multiple controls with same bindings in single xaml

我有一个 xaml 和一个带有两个选项卡的 TabControl。每个 TabItems 都有一个 treeview 具有完全相同的代码。绑定、VM 等完全相同。它们根据 属性 处理在我的模型中处理的不同数据。所以我的VM和View就不用管了。

有什么方法可以让我编写 treeviewHierarchicalDataTemplate 一次并且每个选项卡都引用而不是在同一个 xaml 中重复代码?

类似

<TabControl>
    <TabItem Header="Tab1">
        <Grid>
           <!-- Refer to the tree view here -->      
        </Grid>
    </TabItem>

    <TabItem Header="Tab2">
        <Grid>
           <!-- Refer to the tree view here -->      
        </Grid>
    </TabItem>
</TabControl>

但是 treeviewHierarchicalDataTemplate 如何写然后引用它们?

定义一个包含您的 TreeView 布局的 DataTemplate,然后使用 ContentPresenterContentControl 来呈现它:

<Window.Resources>
    <DataTemplate x:Key="TreeTemplate">
        <Your TreeViewLayout ...>
    </DataTemplate>
</Window.Resources>

...    

<TabControl>
    <TabItem Header="Tab1">
       <ContentControl Content="{Binding}" ContentTemplate="{StaticResource TreeTemplate}" />   
    </TabItem>

    <TabItem Header="Tab2">
        <ContentControl Content="{Binding}" ContentTemplate="{StaticResource TreeTemplate}" />     
    </TabItem>
</TabControl>