詳解WPF如何顯示具有層級關(guān)系的數(shù)據(jù)
前言
比方說我們有以下兩個類:
public class Class
{
public string? Name { get; set; }
public List<Student>? Students { get; set; }
}
public class Student
{
public string? Name { get; set; }
}
一個表示班級,一個表示學(xué)生,一個班級包含多個學(xué)生。在WPF中我們該如何顯示這種具有層級關(guān)系的數(shù)據(jù)呢?
今天給大家介紹的是用TreeView與HierarchicalDataTemplate進行顯示。
實現(xiàn)效果如下所示:

如果你對此感興趣,可以接著往下閱讀。
創(chuàng)建數(shù)據(jù)
private void Button_Click(object sender, RoutedEventArgs e)
{
Student student1 = new Student() { Name = "小明" };
Student student2 = new Student() { Name = "小紅" };
Student student3 = new Student() { Name = "小黃" };
Student student4 = new Student() { Name = "小綠" };
Student student5 = new Student() { Name = "小剛" };
List<Student> students1 = new List<Student>()
{
student1,
student2,
student3
};
List<Student> students2 = new List<Student>()
{
student4,
student5
};
Class class1 = new Class()
{
Name = "班級1",
Students = students1
};
Class class2 = new Class()
{
Name = "班級2",
Students = students2
};
List<Class> classes = new List<Class>()
{
class1,
class2
};
DataContext = classes;
}
數(shù)據(jù)模板的使用
xaml:
<TreeView>
<TreeViewItem ItemsSource="{Binding}" Header="全部班級"/>
</TreeView>
HierarchicalDataTemplate介紹
HierarchicalDataTemplate是WPF(Windows Presentation Foundation)中的一種數(shù)據(jù)模板,用于在樹狀結(jié)構(gòu)或?qū)哟谓Y(jié)構(gòu)中顯示數(shù)據(jù)。它允許您定義如何呈現(xiàn)包含子項的數(shù)據(jù)對象。
通過HierarchicalDataTemplate,您可以指定一個模板,用于呈現(xiàn)數(shù)據(jù)對象本身,以及一個模板,用于呈現(xiàn)其子項。這使得在TreeView等控件中輕松顯示復(fù)雜的數(shù)據(jù)結(jié)構(gòu),如文件夾和文件、組織架構(gòu)等。
通常,您會在ItemsSource屬性中指定數(shù)據(jù)源,然后使用HierarchicalDataTemplate定義每個級別的數(shù)據(jù)對象應(yīng)該如何呈現(xiàn)。
通過使用HierarchicalDataTemplate,您可以更靈活地控制數(shù)據(jù)的呈現(xiàn)方式,使您能夠創(chuàng)建具有深層次結(jié)構(gòu)的動態(tài)UI。
HierarchicalDataTemplate的使用
xaml:
<Window.Resources>
<HierarchicalDataTemplate DataType = "{x:Type local2:Class}"
ItemsSource = "{Binding Path=Students}">
<TextBlock Text="{Binding Path=Name}"/>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type local2:Student}">
<TextBlock Text="{Binding Path=Name}"/>
</DataTemplate>
</Window.Resources>
我們可以發(fā)現(xiàn)對于Class類,使用了一個HierarchicalDataTemplate,ItemsSource綁定的是Class類的Students屬性。
Student類并沒有再含有層次數(shù)據(jù)了所有直接使用DataTemplate就好了。
查看實現(xiàn)效果
最后實現(xiàn)的效果如下所示:

總結(jié)
在日常開發(fā)過程中,我們可能也會有顯示層級數(shù)據(jù)的需求,本文通過一個簡單的Demo,介紹了在WPF中通過TreeView控件與HierarchicalDataTemplate層級數(shù)據(jù)模板進行層級數(shù)據(jù)的顯示。
到此這篇關(guān)于詳解WPF如何顯示具有層級關(guān)系的數(shù)據(jù)的文章就介紹到這了,更多相關(guān)WPF顯示層級關(guān)系數(shù)據(jù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
在C#中List集合使用First()方法獲取第一個元素的操作
這篇文章主要介紹了在C#中List集合使用First()方法獲取第一個元素的操作,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-12-12

