首页 > 解决方案 > wpf how to binding one TreeView to another TreeView

问题描述

I'm trying to bind TreeView t2 to TreeView t1 in xaml as below:

<Window x:Class="WpfApp2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp2"
    mc:Ignorable="d"
    Title="MainWindow" Height="620" Width="600">
<Window.Resources>
    <HierarchicalDataTemplate DataType="{x:Type TreeViewItem}" ItemsSource="{Binding Items}">
        <StackPanel Orientation="Horizontal" >
            <TextBlock Background="AliceBlue" Text="{Binding Path=Header, Mode=TwoWay}" Width="220"/>
        </StackPanel>
    </HierarchicalDataTemplate>
</Window.Resources>
<StackPanel>
    <TreeView x:Name="t1">
        <TreeView.Items>
            <TreeViewItem Header="a"></TreeViewItem>
            <TreeViewItem Header="b"></TreeViewItem>
        </TreeView.Items>
    </TreeView>
    <TreeView x:Name="t2" ItemsSource="{Binding Items, ElementName=t1}"></TreeView>
</StackPanel>

I expected t2 will have the same number of nodes with t1. But the result is that, all nodes of t1 are deleted. Why?

I expected result:

enter image description here

The actual result:

enter image description here

标签: c#wpftreeview

解决方案


我预计t2将具有相同数量的节点t1。但结果是,所有的节点t1都被删除了。为什么?

因为视觉元素的实例,例如 aTreeViewItem只能在视觉树中出现一次。一个元素只能有一个可视父级,在这种情况下,项目将从第一个中删除TreeView并添加到第二个中。

因此,您需要克隆TreeViewItem您希望能够在两者中显示的每个元素TreeViews


推荐阅读