I have a class called ClassWithPupils
which looks like:
public class ClassWithPupils : ViewModelBase
{
public ClassWithPupils(IClass @class)
{
Class = @class;
Pupils = new ObservableCollection<IPupil>();
}
public IClass Class
{
get { return Get<IClass>(); }
set { Set(value); }
}
public ObservableCollection<IPupil> Pupils
{
get { return Get<ObservableCollection<IPupil>>(); }
set { Set(value); }
}
}
And I have a ViewModel which contains an ObservableCollection<ClassWithPupils>
.
private ObservableCollection<ClassWithPupils> classesWithPupils;
public ObservableCollection<ClassWithPupils> ClassesWithPupils
{
get { return classesWithPupils ?? (classesWithPupils = new ObservableCollection<ClassWithPupils>()); }
}
This collection is filled correct with items from a Database.
Now I want to display all items from ClassesWithPupils hierarchical in a TreeView
.
My View so far looks like:
<TreeView ItemsSource="{Binding ClassesWithPupils, UpdateSourceTrigger=PropertyChanged}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding}">
<Label Content="{Binding Class.Name}"/>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
So the Class-Names are displayed correct.
Unfortunately I have no clue how to bind the Pupils-Collection of each ClassWithPupils-Entry to the correct item in the TreeView as children.
I tried something like:
<TreeView ItemsSource="{Binding ClassesWithPupils, UpdateSourceTrigger=PropertyChanged}">
<TreeView.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding}">
<Label Content="{Binding Class.Name}"/>
<HierarchicalDataTemplate.ItemTemplate>
<HierarchicalDataTemplate ItemsSource="{Binding Pupils}">
<Label Content="{Binding Name}"/>
</HierarchicalDataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
</HierarchicalDataTemplate>
</TreeView.ItemTemplate>
</TreeView>
With no success...
So my question is: How can I display the Name of the Pupils as children of the classes in the TreeView?
After looking at your code I have spotted only one error in binding, that could cause the described problem, you should bind to Pupils inside the hierarchical template like this: