The HierarchicalDataTemplate doesn't show children - why not?
I'm trying to make it as simple as possible HierarchicalDataTemplate
to bind nested data with WPF TreeView
. For some reason, the children of my tree are not visible:
Here's the whole XAML:
<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:src="clr-namespace:WpfApplication1"
Title="MainWindow" Height="350" Width="525">
<TreeView Name="ctTree">
<TreeView.Resources>
<HierarchicalDataTemplate DataType = "{x:Type src:MyClass}"
ItemsSource = "{Binding Path=Children}">
<TextBlock Text="{Binding Path=Name}"/>
</HierarchicalDataTemplate>
</TreeView.Resources>
</TreeView>
</Window>
and heres all the C # behind this except apps and namespace:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
var collection = new ObservableCollection<MyClass>
{
new MyClass { Name = "parent one" },
new MyClass { Name = "parent two" },
};
collection[0].Children.Add(new MyClass { Name = "child one" });
collection[0].Children.Add(new MyClass { Name = "child two" });
ctTree.ItemsSource = collection;
}
}
class MyClass
{
public string Name { get; set; }
public ObservableCollection<MyClass> Children
= new ObservableCollection<MyClass>();
}
Note that the data template does indeed apply to elements: the data is taken from the property Name
, and if the template was not applied, it will appear as "MyClass".
How can I show the children? I seem to be doing the same as all the examples on HierarchicalDataTemplate
.
source to share
MyClass.Children
is a field, not a property. You cannot bind to a field, convert a field Children
to a property and everything should work then:
class MyClass
{
public string Name { get; set; }
public ObservableCollection<MyClass> Children { get; private set; }
public MyClass()
{
Children = new ObservableCollection<MyClass>();
}
}
source to share