Associate Wpf HierarchicalDataTemplate ItemsSource with CollectionViewSource in a Dictionary?

I am trying to show a Wpf Treeview with elements sorted by CollectionViewSource.

Currently everything works, except for sorting using this code in my resource dictionary:

<HierarchicalDataTemplate DataType="{x:Type books:Container}" ItemsSource="{Binding Path=Items}">
    <nav:ContainerControl />
</HierarchicalDataTemplate>

What will be the syntax for changing the HierarchicalDataTemplate to bind to the CollectionViewSource, which in turn pulls from the Items property?

I tried the code options posted on the Bea Stollnitz blog without success. I cannot figure out how to set the CollectionViewSource.

+3
source share
2 answers

, , , . , WPF . , ViewModel , Items CollectionView ViewModel .

. , HierarchicalDataTemplate , Binding. XAML.

<HierarchicalDataTemplate DataType="{x:Type books:Container}"
    ItemsSource="{Binding Items, Converter={x:Static local:CollectionViewConverter.Instance}}">
    <nav:ContainerControl />
</HierarchicalDataTemplate>

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;
    }
}
+5

, , Items ListCollectionView:

private SortDescription _ItemsLcvSortDesc;
    private SortDescription ItemsLcvSortDesc
    {
        get
        {
            if (_ItemsLcvSortDesc == null)
                _ItemsLcvSortDesc = new SortDescription("SortOrder", ListSortDirection.Ascending);
            return _ItemsLcvSortDesc;
        }
    }

    private ListCollectionView _ItemsLcv;
    public ListCollectionView ItemsLcv
    {
        get
        {
            if (_ItemsLcv == null)
                _ItemsLcv = CollectionViewSource.GetDefaultView(Items) as ListCollectionView;
            _ItemsLcv.SortDescriptions.Add(ItemsLcvSortDesc);
            return _ItemsLcv;
        }
    }

- ?

0

Source: https://habr.com/ru/post/1729007/


All Articles