How to sort TreeView items using SortDescriptions in Xaml?

后端 未结 3 679
粉色の甜心
粉色の甜心 2020-11-30 11:38

I have a list of Layers binded to a TreeView where each instance has a list of Effects. I show them via a HierarchicalDataTemplate whi

3条回答
  •  抹茶落季
    2020-11-30 12:23

    This is not the XAML based solution, but I was facing the same problem and found the solution like below,

    I am assuming you have 3 classes like below: AllLayers, Layers & Effects

    class AllLayers
    {
        public AllLayers()
        {
            layers = new ObservableCollection();
            var collectionView = CollectionViewSource.GetDefaultView(layers);
            collectionView.SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
            collectionView.SortDescriptions.Add(new SortDescription("Color", ListSortDirection.Ascending));
        }
        public ObservableCollection layers { get; }
    }
    class Layers
    {
        public Layers(string name, string color)
        {
            Name = name;
            Color = color;
            CollectionViewSource.GetDefaultView(effects).SortDescriptions.Add(new SortDescription("Name", ListSortDirection.Ascending));
        }
        public string Name { get; set; }
        public string Color { get; set; }
        public ObservableCollection effects { get; }
    }
    class Effects
    {
        public string Name { get; set; }
    }
    

    After that, your existing binding should work with sorting. No need of change to your XAML or anything.

提交回复
热议问题