将多个TreeView绑定到同一个ItemSource

时间:2017-08-17 15:51:36

标签: c# wpf xaml binding treeview

我正在尝试将多个TreeView绑定到包含TreeViewItems的同一ItemSource。每当我这样做时,最后一个要加载的是唯一一个显示项目的。 (因此,如果我按特定顺序声明了三个树视图,则声明的最后一个将是唯一显示项目的视图。)

这是一个示例WPF项目,我创建了默认设置来显示它:

XAML:

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        <TreeView x:Name="TreeOne" ItemsSource="{Binding TreeItems}" HorizontalAlignment="Left" Height="300" Margin="10,10,0,0" VerticalAlignment="Top" Width="238"/>
        <TreeView x:Name="TreeTwo" ItemsSource="{Binding TreeItems}" HorizontalAlignment="Left" Height="300" Margin="10,10,0,0" VerticalAlignment="Top" Width="239" Grid.Column="1"/>
    </Grid>
</Window>

Code Behind :(我在实际项目中使用MVVM,但这有相同的错误)

using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Windows.Controls;

namespace WpfApplication1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            TreeItems = new ObservableCollection<TreeViewItem>() { new TreeViewItem() { Header = "First item" } };
            InitializeComponent();
        }

        public ObservableCollection<TreeViewItem> TreeItems { get; set; }
    }
}

picture of the output of the above code

如果我注释掉第二棵树,第一棵树将正确显示。

1 个答案:

答案 0 :(得分:2)

TreeViewItem是控件,无法在多个可视树中同时显示(与TreeView不同!)。要解决此问题,请使用字符串集合(new ObservableCollection<string> { "First item" };)。如果您的可视化具有复杂的数据对象使用模板功能,例如:

TreeItems = new ObservableCollection<DateTime>() 
{ 
  new DateTime(2017, 1, 1), 
  new DateTime(2017, 12, 31) 
};

XAML

<Window.Resources>

    <DataTemplate x:Key="DateItem">
        <StackPanel Orientation="Horizontal">
            <TextBlock Text="{Binding Path=Year}"/>
            <Border Background="Green" Width="2" Height="2"/>
            <TextBlock Text="{Binding Path=Month}"/>
            <Border Background="Green" Width="2" Height="2"/>
            <TextBlock Text="{Binding Path=Day}"/>
        </StackPanel>            
    </DataTemplate>

</Window.Resources>

<TreeView x:Name="TreeOne" ItemTemplate="{StaticResource DateItem}"/>
<TreeView x:Name="TreeTwo" ItemTemplate="{StaticResource DateItem}"/>