I have a wpf treeview bound to collection. The model collection is of type:
public Class A {
public string Name {get; set}
public ObservableCollection< B> Bs {get; set;}
}
public Class B {
public ObservableCollection< C> Cs {get; set;}
}
public Class C {
public string Name {get; set;}
}
XAML:
<my:AConverter x:Key="AConverter"/>
<DataTemplate DataType="{x:Type C}">
<TextBlock Text="{Binding Name}"/>
</DataTemplate>
<HierarchicalDataTemplate DataType="{x:Type A}"
ItemsSource="{Binding Converter={StaticResource AConverter}}">
<TextBlock Text="{Binding Name}"/>
</HierarchicalDataTemplate>
<treeView Grid.Row="0" ItemsSource="{Binding As}"/>
AConverter.cs:
public class AConverter: IValueConverter {
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
if (value is A) {
return (value as A).Bs.SelectMany(b => b.Cs);
}
return null;
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) {
throw new NotImplementedException();
}
}
The output expected is: A->C in treeview and not B. The issue here is when we add a new C the converter is not getting called to show the same in tree hierarchy
You loose the updates if you apply a converter which does not return an observable collection [sic]. What you try to achieve is a bit of a pain really, basically you need to flatten the hierarchy while maintaining updates, this can be done using a
CompositeCollectionto some degree. e.g.The implementation of the other cases is up to you, the insertions seem to work.
A better solution might be to expose
CompositeCollectionsat every level, because then they can easily be nested, i.e. you can add aCollectionContainerhaving aCompositeCollectionas its source.