Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I bind a WPF TreeView to a single root node?

Say I have a binary tree, where the root of the data structure is just a tree node. For each node, the children are accessible through the Children property. Here's what I tried. The TreeRoot is a property of the inherited data context, but it's a single node (not a collection).

<UserControl.Resources>
    <HierarchicalDataTemplate x:Key="TreeNodeTemplate" ItemsSource="{Binding Children}">
        <TextBlock Text="{Binding Name}" />
    </HierarchicalDataTemplate>
</UserControl.Resources>

<Grid>
    <TreeView ItemsSource="{Binding TreeRoot}" ItemTemplate="{StaticResource TreeNodeTemplate}" />
</Grid>
like image 835
Sam Harwell Avatar asked Jan 30 '10 20:01

Sam Harwell


People also ask

What is TreeView in WPF?

The TreeView control provides a way to display information in a hierarchical structure by using collapsible nodes. This topic introduces the TreeView and TreeViewItem controls, and provides simple examples of their use.


1 Answers

I had this problem and concluded that I couldn't bind a non-collection to a treeview as a way to specify the root node. So what I did was to make a quick change to my ModelView and make the property representing the root node a collection of 1 item.

public class ContainerViewModel
{
   public ObservableCollection<TreeNodeViewModel> RootNodes { get; private set; }

   public ContainerViewModel()
   {
      // Create a single node in the collection of root nodes
      RootNodes = new ObservableCollection<TreeNodeViewModel>();
      RootNodes.Add(new TreeNodeViewModel());
   }
}

public class TreeNodeViewModel
{
   public ObservableCollection<TreeNodeViewModel> Children { get; set; }
}

I used an ObservableCollection<> above but might make more sense to use something cheaper like a List<> since you don't expect the collection to change (at least in your scenario).

like image 157
Emmanuel Avatar answered Oct 10 '22 05:10

Emmanuel