WPF:正确地将对象存储在TreeViewItem中 [英] WPF: Correctly storing an object in a TreeViewItem
问题描述
要在TreeViewItem中存储一个对象(比如一个类的实例),我目前将该对象存储在 TreeViewItem
的头
,然后覆盖该类的 ToString
方法,以便它显示正确的字符串头;
To store an object (say, an instance of a class) in a TreeViewItem, I am currently storing the object in the TreeViewItem
's Header
and then overriding the ToString
method of that class, so that it displays the correct string header; I then cast the object back during an event.
这是正确的方式来实现这种事情,有没有更好,更正确的方法?
Is this the correct way to achieve this sort of thing, or is there any better, more proper way ?
推荐答案
正确的方式是只需添加 () Items
集合并使用 HierarchicalDataTemplate
来控制项目的呈现方式:
The "proper" way is to just add the object
to the TreeView
's (or TreeViewItem
's) Items
collection and use a HierarchicalDataTemplate
to control how the item is rendered:
em> Person.cs :
Person.cs:
public class Person
{
private readonly ICollection<Person> _children = new ObservableCollection<Person>();
public string Name { get; set; }
public ICollection<Person> Children
{
get
{
return _children;
}
}
}
Window1.xaml .cs :
public Window1()
{
InitializeComponent();
var people = new List<Person>();
var kent = new Person() { Name = "Kent" };
kent.Children.Add(new Person() { Name = "Tempany" });
people.Add(kent);
_treeView.ItemsSource = people;
}
Window1.xaml :
<TreeView x:Name="_treeView">
<TreeView.Resources>
<HierarchicalDataTemplate DataType="{x:Type local:Person}" ItemsSource="{Binding Children}">
<TextBlock Text="{Binding Name}"/>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
这篇关于WPF:正确地将对象存储在TreeViewItem中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!