Binding arbitary depth tree to a TreeView
I've got the following interface (as you can see, I'm adapting the MVVM pattern a bit):
public interface IViewModel {
string Header { get; }
IEnumerable<IViewModel> Nodes { get; }
}
I want to bind this datatype to a treeview, with a single top node and an arbitary depth. Header
is the text to display in each node, and Nodes
are the child nodes.
I've got the following XAML:
<TreeView ItemsSource="{Binding开发者_运维百科}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate DataType="{x:Type ViewModel:IViewModel}" ItemsSource="{Binding Nodes}">
<TextBlock Text="{Binding Header}" />
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
and setting the top-level node to the DataContext of the Window:
IViewModel model = ViewModelFactory.GetTopLevelViewModel();
DataContext = model;
However, nothing is appearing in the treeview. I've looked at quite a few similar questions on SO and elsewhere, but none seem to solve my problem. A few questions:
- Why do I need to set the
DataContext
of the parent Window, and not the TreeView itself? - Why is nothing appearing in the treeview?
- How do I fix it?
Why do I need to set the DataContext of the parent Window, and not the TreeView itself?
You don't need to. You can set the data context on the TreeView
itself:
<TreeView x:Name="tree"...>
-
IViewModel model = ViewModelFactory.GetTopLevelViewModel();
tree.DataContext = model;
Why is nothing appearing in the treeview?
TreeView
is an ItemsControl
. In order to make it display something you need to assign its ItemsSource
property to a collection.
How do I fix it?
For example, you can set the DataContext
to a collection of IViewModel
items instead of a single item:
IViewModel model = ViewModelFactory.GetTopLevelViewModel();
tree.DataContext = new IViewModel[] { model };
精彩评论