如何使用 Xaml 中的 SortDescriptions 对 TreeView 项目进行排序? [英] How to sort TreeView items using SortDescriptions in Xaml?

查看:23
本文介绍了如何使用 Xaml 中的 SortDescriptions 对 TreeView 项目进行排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个绑定到 TreeViewLayers 列表,其中每个实例都有一个 Effects 列表.我通过 HierarchicalDataTemplate 向它们展示效果很好,但我正在尝试使用 SortDescriptions 对它们进行排序.

I have a list of Layers binded to a TreeView where each instance has a list of Effects. I show them via a HierarchicalDataTemplate which works great but I am trying to sort them using SortDescriptions.

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

I don't know how to do this in xaml but doing this sorts only the first level of items, not the sub items:

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

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

I am trying to sort them first by .Color, then by .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>

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

But this still only does it for the first level of hierarchy. How can I specify it for each layer.Effects collection?

推荐答案

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

I would suggest to use converter to sort sub items. Something like this:

<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>

和转换器:


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

这篇关于如何使用 Xaml 中的 SortDescriptions 对 TreeView 项目进行排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆