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

Joa*_*nge 9 .net c# sorting wpf xaml

我有一个Layersbinded 列表TreeView,每个实例都有一个列表Effects.我通过HierarchicalDataTemplate显示它们,它工作得很好,但我正在尝试使用它们进行排序SortDescriptions.

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

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

我试图先将它们排序.Color,然后依次排序.Name.

有任何想法吗?

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

<Window.Resources>

    <CollectionViewSource x:Key="SortedLayers" Source="{Binding AllLayers}">
        <CollectionViewSource.SortDescriptions>
            <scm:SortDescription PropertyName="Color" />
            <scm:SortDescription PropertyName="Name" />
        </CollectionViewSource.SortDescriptions>
    </CollectionViewSource>

</Window.Resources>
Run Code Online (Sandbox Code Playgroud)

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

小智 19

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

<TreeView Name="treeCategories" Margin="5" ItemsSource="{Binding Source={StaticResource SortedLayers}}">
<TreeView.ItemTemplate>
    <HierarchicalDataTemplate ItemsSource="{Binding Effects, Converter={StaticResource myConverter}, ConverterParameter=EffectName}">
        <TextBlock Text="{Binding Path=LayerName}" />
        <HierarchicalDataTemplate.ItemTemplate>
            <DataTemplate>
                <TextBlock Text="{Binding Path=EffectName}" />
            </DataTemplate>
        </HierarchicalDataTemplate.ItemTemplate>
    </HierarchicalDataTemplate>
</TreeView.ItemTemplate>
Run Code Online (Sandbox Code Playgroud)

和转换器:


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;
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 只是一个很小的改进,将 System.Collections.IList 的值更改为 (System.Collections.IList)value 以避免在 value 不是 IList 时出现空引用异常(您应该有一个 InvalidCastException) (2认同)