我准备了小样本来复制这个..
<Window x:Class="TestApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:this="clr-namespace:TestApp"
Title="MainWindow" Height="350" Width="525">
<Window.DataContext>
<this:TreeViewModel />
</Window.DataContext>
<Window.Resources>
<HierarchicalDataTemplate ItemsSource="{Binding Courses}" DataType="{x:Type this:Department}">
<Label Content="{Binding DepartmentName}"/>
</HierarchicalDataTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Books}" DataType="{x:Type this:Course}">
<Label Content="{Binding CourseName}"/>
</HierarchicalDataTemplate>
<DataTemplate DataType="{x:Type this:Book}">
<Label Content="{Binding BookName}"/>
</DataTemplate>
</Window.Resources>
<Grid>
<TreeView ItemsSource="{Binding Departments}">
</TreeView>
</Grid>
</Window>
模型和视图模型类。
public class Book :ViewModelBase
{
private string bookname = string.Empty;
public string BookName
{
get
{
return bookname;
}
set
{
bookname = value;
OnPropertyChanged("BookName");
}
}
public Book(string bookname)
{
BookName = bookname;
}
}
部门班
public class Department : ViewModelBase
{
private List<Course> courses;
public Department(string depname)
{
DepartmentName = depname;
Courses = new List<Course>()
{
new Course("Course1"),
new Course("Course2")
};
}
public List<Course> Courses
{
get
{
return courses;
}
set
{
courses = value;
OnPropertyChanged("Courses");
}
}
public string DepartmentName
{
get;
set;
}
}
课程班
public class Course :ViewModelBase
{
private List<Book> books;
public Course(string coursename)
{
CourseName = coursename;
Books = new List<Book>()
{
new Book("JJJJ"),
new Book("KKKK"),
new Book("OOOOO")
};
}
public List<Book> Books
{
get
{
return books;
}
set
{
books = value;
OnPropertyChanged("Books");
}
}
public string CourseName
{
get;
set;
}
}
树视图模型类。
public class TreeViewModel :ViewModelBase
{
private List<Department> departments;
public TreeViewModel()
{
Departments = new List<Department>()
{
new Department("Department1"),
new Department("Department2")
};
}
public List<Department> Departments
{
get
{
return departments;
}
set
{
departments = value;
OnPropertyChanged("Departments");
}
}
}
ViewModelBase 类。
public class ViewModelBase :INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public void OnPropertyChanged(string propname)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propname));
}
}
}
最后它以分层格式显示数据..我希望这会让你满意......