[英]Creating treeview binding wpf
I have been trying to make a treeview that looks something like 我一直在尝试制作一个看起来像
2001(root) 2001(根)
-Student1(node) -Student1(节点)
-Student2(node) -Student2(节点)
I've tried to use hierarchicaldatatemplates but I'm still not grasping what I need to. 我已经尝试使用hierarchicaldatatemplates,但是我仍然没有掌握我所需要的。 This is my code that i'm looking to bind my treeview to.
这是我想要将树视图绑定到的代码。 Any help with the Xaml would be appriciated.
Xaml的任何帮助都将适用。
I thought it would look something like 我以为看起来像
<TreeView ItemsSource="{Binding CurrentClass}">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:Student}" ItemsSource="{Binding CurrentClass.Students}">
<TextBlock Text="{Binding CurrentClass.Students/FirstName}" />
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
public class ViewModel
{
public FreshmenClass currentClass = new FreshmenClass();
public ViewModel()
{
currentClass.Year = "2001";
currentClass.Students.Add(new Student("Student1", "LastName1"));
currentClass.Students.Add(new Student("Student2", "LastName2"));
}
public FreshmenClass CurrentClass
{
get { return currentClass; }
}
}
public class FreshmenClass
{
public string Year { get; set; }
public List<Student> students = new List<Student>();
public List<Student> Students
{
get { return students; }
set { students = value; }
}
}
public class Student
{
public string FirstName { get; set; }
public string LastName { get; set; }
public Student(string firstName, string lastName)
{
FirstName = firstName;
LastName = lastName;
}
}
Take a look to the documentation about Treeview and HierarchicalDataTemplate. 查看有关Treeview和HierarchicalDataTemplate的文档。 Anyway I edit your example like this (XAML):
无论如何,我编辑这样的示例(XAML):
<TreeView ItemsSource="{Binding CurrentClass}" >
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Students}">
<TextBlock Text="{Binding Year}" />
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding FirstName}"> </TextBlock>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
and c#: 和C#:
public class ViewModel
{
private List<FreshmenClass> currentClass;
public ViewModel()
{
CurrentClass = new List<FreshmenClass>();
FreshmenClass temp = new FreshmenClass();
temp.Year = "2001";
temp.Students.Add(new Student("Student1", "LastName1"));
temp.Students.Add(new Student("Student2", "LastName2"));
CurrentClass.Add(temp);
}
public List<FreshmenClass> CurrentClass
{
get { return currentClass; }
set { currentClass = value; }
}
}
the ItemsSource property is an IEnumerable. ItemsSource属性是IEnumerable。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.