在 WPF 中设置具有 2 个级别的 TreeView HierarchicalDataTemplate [英] Set TreeView HierarchicalDataTemplate with 2 levels in WPF

查看:51
本文介绍了在 WPF 中设置具有 2 个级别的 TreeView HierarchicalDataTemplate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个在窗口的 DataContext 中表示的视图模型.

I have a View Model that is represented in the DataContext of the window.

public class SchoolViewModel:ViewModelBase
{
      public ObservableCollection<SchoolClassGroup> ClassesCollection { get; set; }
            ....             
} 


public class SchooleClassGroup:ViewModelBase
{
     public string ClassName {get;set;}
     public string TeacherName {get;set;}
     public ObservableCollection<Students> StudentCollection{ get; set; }

}

public class Student
{
     public string Name {get;set;}
     public int Age {get;set;}
     public DateTime BirthDate {get;set;}
     ...
} 

我想代表一个 TreeView,它将向我展示学校、班级和学生.

I want to represent a TreeView that will show me schools,class and students.

我该怎么做?

谢谢!

推荐答案

您需要为具有父子关系的对象树的每个级别创建 HeirarchicalDataTemplates,并为叶节点添加一个简单的 DataTemplate.

You need to create HeirarchicalDataTemplates for each level of your object tree that has a Parent-Child relationship, plus a simple DataTemplate for the leaf node.

你的对象树应该是 School -> Class -> Student

Your object tree should be School -> Class -> Student

班级学校有一个

List<Class>

class 类有一个

List<Student>

那就简单了

<Window.Resources>

        <HierarchicalDataTemplate ItemsSource="{Binding Classes}" DataType="{x:Type School}">
            <TextBlock Text="{Binding Name}" />
        </HierarchicalDataTemplate>

        <HierarchicalDataTemplate ItemsSource="{Binding Students}" DataType="{x:Type Class}">
            <TextBlock Text="{Binding Name}" />
        </HierarchicalDataTemplate>

        <DataTemplate DataType="{x:Type Student}">
            <TextBlock Text="{Binding Name}" />
        </DataTemplate >

    </Window.Resources>

    <Grid>
        <TreeView ItemsSource="{Binding Schools}" >
    </Grid>

这篇关于在 WPF 中设置具有 2 个级别的 TreeView HierarchicalDataTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆