Bind a Wpf HierarchicalDataTemplate ItemsSource to a CollectionViewSource in a dictionary?

awx*_*awx 3 data-binding wpf hierarchicaldatatemplate collectionviewsource

I'm trying to display a Wpf Treeview with items sorted by a CollectionViewSource.

Currently, everything is working except sorting using this code in my resource dictionary:

<HierarchicalDataTemplate DataType="{x:Type books:Container}" ItemsSource="{Binding Path=Items}">
    <nav:ContainerControl />
</HierarchicalDataTemplate>
Run Code Online (Sandbox Code Playgroud)

What would be the syntax for changing the HierarchicalDataTemplate to bind to a CollectionViewSource that in turn pulls from the Items property?

I've tried variations of the code posted on Bea Stollnitz's blog with no success. I can't figure out how to set the source of the CollectionViewSource.

Jos*_*osh 6

好吧,我只想说我讨厌我提出的解决方案,但确实有效.也许WPF大师会用更好的选择来启发我们.当然,如果您在视图后面使用ViewModel,您可以使用ViewModel中的CollectionView简单地包装模型的Items属性并完成它.

但这是另一种解决方案.基本上,除了将转换器添加到绑定之外,您的HierarchicalDataTemplate可以保持原样.我实现了以下转换器并相应地更改了XAML.

<HierarchicalDataTemplate DataType="{x:Type books:Container}"
    ItemsSource="{Binding Items, Converter={x:Static local:CollectionViewConverter.Instance}}">
    <nav:ContainerControl />
</HierarchicalDataTemplate>
Run Code Online (Sandbox Code Playgroud)

CollectionViewConverter.cs

public class CollectionViewConverter : IValueConverter
{

    public CollectionViewConverter() {}

    static CollectionViewConverter(){
        Instance = new CollectionViewConverter();
    }

    public static CollectionViewConverter Instance {
        get;
        set;
    }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        var view = new ListCollectionView((System.Collections.IList)value);
        view.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
        return view;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        // not really necessary could just throw notsupportedexception
        var view = (CollectionView)value;
        return view.SourceCollection;
    }
}
Run Code Online (Sandbox Code Playgroud)