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:
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>
HTH,
Kent