Expand Wpf Treeview to support Sorting

前端 未结 3 1138
深忆病人
深忆病人 2021-01-21 09:48

Hi I created this small example, and I would like to expand it to support Sorting.

public class Country
{
    public string Name { get; set; }
    public int Sor         


        
3条回答
  •  Happy的楠姐
    2021-01-21 09:58

    I don't think there is a default sort for TreeViews. You can either sort the items prior to entering them into the collection, or overwrite the ObservableCollection to include a Sort method.

    I overwrite it in one of my projects:

    public class SortableObservableCollection : ObservableCollection
    {
        // Constructors
        public SortableObservableCollection() : base(){}
        public SortableObservableCollection(List l) : base(l){}
        public SortableObservableCollection(IEnumerable l) :base (l) {}
    
        #region Sorting
    
        /// 
        /// Sorts the items of the collection in ascending order according to a key.
        /// 
        /// The type of the key returned by .
        /// A function to extract a key from an item.
        public void Sort(Func keySelector)
        {
            InternalSort(Items.OrderBy(keySelector));
        }
    
        /// 
        /// Sorts the items of the collection in descending order according to a key.
        /// 
        /// The type of the key returned by .
        /// A function to extract a key from an item.
        public void SortDescending(Func keySelector)
        {
            InternalSort(Items.OrderByDescending(keySelector));
        }
    
        /// 
        /// Sorts the items of the collection in ascending order according to a key.
        /// 
        /// The type of the key returned by .
        /// A function to extract a key from an item.
        /// An  to compare keys.
        public void Sort(Func keySelector, IComparer comparer)
        {
            InternalSort(Items.OrderBy(keySelector, comparer));
        }
    
        /// 
        /// Moves the items of the collection so that their orders are the same as those of the items provided.
        /// 
        /// An  to provide item orders.
        private void InternalSort(IEnumerable sortedItems)
        {
            var sortedItemsList = sortedItems.ToList();
    
            foreach (var item in sortedItemsList)
            {
                Move(IndexOf(item), sortedItemsList.IndexOf(item));
            }
        }
    
        #endregion // Sorting
    }
    

    You would then sort it by calling something like

    Countries.Sort(country => country.SortOrder);
    

    I like overwriting it because it let me add additional functionality to it as well such as IndexOf or AddRange/RemoveRange

提交回复
热议问题