Grouping child objects in WPF TreeView
You can achieve this effect by binding the ItemsSource
on your HierarchicalDataTempalate
using an IValueConverter
. This converter is simply does the following:
public class MyConverter : IValueConverter
{
public object Convert(object value, ...)
{
return
from item in (IEnumerable<MyItem>)value
group item by item.Type into g
select new { Type = g.Key, Items = g }
}
...
}
Now your HierarchcialDataTemplate
can be as follows:
<HierarchicalDataTemplate ItemsSource="{Binding SomePath, Converter={x:Static local:MyConverter}">
<HierarchicalDataTemplate.ItemTemplate>
<HierarchicalDataTemplate
ItemsSource="{Binding Items}"
TargetType="{x:Type local:MyItem}"
ItemTemplate="{StaticResource MyItemTemplate}">
<!-- may omit ItemTemplate in prior line to use implicit template -->
<TextBlock Text="{Binding Type}" /> <!-- Header for type -->
</HierarchicalDataTemplate>
</HierarchicalDataTemplate.ItemTemplate>
<!-- header for "Object Group #1" -->
</HierarchicalDataTemplate>
Take a look at this article by Mr. Sumi. I'm sure it will help you.