如何使用Xaml中的SortDescriptions对TreeView项进行排序?

我有一个绑定到TreeViewLayers列表,其中每个实例都有一个Effects列表。 我通过HierarchicalDataTemplate显示它们很好,但我试图使用SortDescriptions对它们进行排序。

我不知道如何在xaml中执行此操作,但这样做只排序第一级别的项目,而不是子项目:

 ICollectionView view = CollectionViewSource.GetDefaultView ( treeView1.ItemsSource ); view.SortDescriptions.Add ( new SortDescription ( "Name", ListSortDirection.Ascending ) ); 

我试图先用.Color ,然后按.Name对它们进行排序。

有任何想法吗?

编辑:我添加了这段代码:

         

但这仍然只适用于第一级层次结构。 如何为每个图层指定它。影响集合?

我建议使用转换器对子项进行排序。 像这样的东西:

            

和转换器:

 public class MyConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { System.Collections.IList collection = value as System.Collections.IList; ListCollectionView view = new ListCollectionView(collection); SortDescription sort = new SortDescription(parameter.ToString(), ListSortDirection.Ascending); view.SortDescriptions.Add(sort); return view; } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { return null; } } 

我发现使用多转换器更好:

 using System; using System.Collections; using System.ComponentModel; using System.Globalization; using System.Windows.Data; namespace Converters { [ValueConversion(typeof(object[]), typeof(ListCollectionView))] public class IListToListCollectionViewConverter : IMultiValueConverter { public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture) { var Length = values.Length; if (Length >= 1 && Length < 3) { var IList = values[0] as IList; var SortName = string.Empty; if (Length > 1) SortName = values[1].ToString(); var SortDirection = ListSortDirection.Ascending; if (Length > 2) SortDirection = values[2] is ListSortDirection ? (ListSortDirection)values[2] : (values[2] is string ? (ListSortDirection)Enum.Parse(typeof(ListSortDirection), values[2].ToString()) : SortDirection); var Result = new ListCollectionView(IList); Result.SortDescriptions.Add(new SortDescription(SortName, SortDirection)); return Result; } return null; } public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture) { throw new NotImplementedException(); } } }