WPF TreeView HierarchicalDataTemplate - 绑定到具有不同子集合的对象

Jam*_*ama 3 wpf treeview hierarchicaldatatemplate

我正在尝试TreeView使用数据模板将集合绑定到wpf 控件.集合中的每个项目(人物)还包含两种不同的汽车和书籍集合(汽车,书籍).

这是节省空间所涉及的对象的简化列表.

public class Person
{
  public string Name
  public List<Book> Books;
  public List<Car> Cars;
}

public class Book
{
  public string Title
  public string Author
}

public class Car
{
  public string Manufacturer;
  public string Model;
}
Run Code Online (Sandbox Code Playgroud)

这就是我的约束力

    public MainWindow()
    {
        InitializeComponent();

        this.treeView1.ItemsSource = this.PersonList();
    }

    public List<Person> PersonList()
    {
        List<Person> list = new List<Person>();


        Book eco = new Book { Title = "Economics 101", Author = "Adam Smith"};
        Book design = new Book { Title = "Web Design", Author = "Robins" };

        Car corola = new Car { Manufacturer = "Toyota", Model = "2005 Corola"};
        Car ford = new Car { Manufacturer = "Ford", Model = "2008 Focus"};

        Person john = new Person { Name = "John", Books = new ObservableCollection<Book> { eco, design }, Cars = new ObservableCollection<Car> { corola } };

        Person smith = new Person { Name = "Smith", Books = new ObservableCollection<Book> { eco, design }, Cars = new ObservableCollection<Car> { ford } };

        list.AddRange(new[] {john, smith });
        return list;
    }
Run Code Online (Sandbox Code Playgroud)

这是Xaml代码

<Grid>
    <TreeView  Name="treeView1">
    </TreeView>
</Grid>
Run Code Online (Sandbox Code Playgroud)

我希望看到树形显示看起来像这样.

>John
  >Books
    Economics 101 : Adam Smith
    Web Design    : Robins
  >Cars
    Totota : 2005 Corola
>Smith
  >Books
    Economics 101 : Adam Smith
    Web Design    : Robins
  >Cars
    Ford: 2008 Focus
Run Code Online (Sandbox Code Playgroud)

此标志 > 用于显示树文件夹,不应在模板中考虑.

oll*_*SFT 7

由于您的树有两个不同的子集合,因此它有点复杂.WPF不支持具有多个ItemsSource定义的方案.因此,您需要将这些集合组合CompositeCollection中.复合元素(即Car,Book)的类型匹配将自动完成.

在XAML中,您需要定义与您的类型定义匹配的所谓HierarchicalDataTemplates.如果local指向名称空间Book,Car并且Person已定义,则简化版HierarchicalDataTemplates可能如下所示:

 <HierarchicalDataTemplate DataType="{x:Type local:Person}" 
                              ItemsSource="{Binding CompositeChildren}">
        <TextBlock Text="{Binding Path=Name}" />
    </HierarchicalDataTemplate>

    <HierarchicalDataTemplate DataType="{x:Type local:Book}">
        <TextBlock Text="{Binding Path=Title}" />
        <!-- ... -->
    </HierarchicalDataTemplate>

    <HierarchicalDataTemplate DataType="{x:Type local:Car}">
        <TextBlock Text="{Binding Path=Model}" />
        <!-- ... -->
    </HierarchicalDataTemplate>
Run Code Online (Sandbox Code Playgroud)

然后,您需要将您的集合连接到树控件.有一些可能性,最简单的方法是在Window类中定义一个属性并定义一个Binding:

<TreeView Items={Binding ElementName=myWindow, Path=Persons}/>
Run Code Online (Sandbox Code Playgroud)

这应该指向正确的方向,但不要把我的代码作为编译就绪:-)