views:

781

answers:

1

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 ?

+4  A: 

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

Kent Boogaart
Thanks for the answer. How do implement a "nested HierarchicalDataTemplate" so to speak? For example, the items in the ItemsSource binding have another list inside of them, and I want the list to be a sublist of them.
Andreas Grech
np Dreas. Can you mark as answer and ask a separate question re the nested HierarchicalDataTemplates?
Kent Boogaart
Hi Kent, will do.
Andreas Grech
http://stackoverflow.com/questions/719609/wpf-having-hierarchicaldatatemplates-in-a-treeview
Andreas Grech