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>
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With