Reputation: 14399
I want to create the hierarchical tree. I followed every step from here, but for some reason it shows me only one level deep. Here's what I get: What could be the reason?
XAML
<TreeView SelectedItemChanged="TreeView_SelectedItemChanged" ItemsSource="{Binding Items}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Children}" DataType="{x:Type local:MyClass}">
<TextBlock Foreground="Red" Text="{Binding Name}" />
<HierarchicalDataTemplate.ItemTemplate>
<DataTemplate>
<TextBlock Text="{Binding Name}" MouseLeftButtonUp="TreeViewItem_MouseLeftButtonUp"/>
</DataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
VIEWMODEL
public class MyClass
{
public string Name { get; set; }
public List<MyClass> Children { get; set; }
}
public class MyViewModel
{
private List<MyClass> _items;
public List<MyClass> Items
{
get
{
return _items;
}
}
public MyViewModel()
{
_items = new List<MyClass>();
_items.Add(new MyClass
{
Name = "1",
Children = new List<MyClass>
{
new MyClass
{
Name = "1_1",
Children = new List<MyClass>
{
new MyClass
{
Name = "1_1_1"
},
new MyClass
{
Name = "1_1_2"
}
}
},
new MyClass
{
Name = "1_2"
}
}
});
}
}
Upvotes: 1
Views: 846
Reputation: 3404
You are defining your template as exactly two levels deep, so you are going to get a two level tree view. This is because you explicitly state that the ItemTemplate
of the HeirarchicalDataTemplate
should be a DataTemplate
with no children.
I am not sure what your intended template is supposed to be, but if you remove that inner template you should get all of the items to display. Alternatively, you could make the inner template also a HeirarchicalDataTemplate
.
Upvotes: 2