如何使用基于实体集合的HierarchicalDataTemplate对WPF TreeView进行排序?

4

我的网页是一个Entity Framework实体。这些实体绑定到WPF TreeView上。我想按照“Sort”属性对TreeView中显示的所有网页进行排序。

代码

EDMX

Entity Framework EDMX entity

它的“Subordinates”属性返回零个或多个网页的集合。

XAML

<TreeView Name="TreeViewWebpages">
    <TreeView.Resources>
        <HierarchicalDataTemplate DataType="{x:Type local:Webpage}"
                                  ItemsSource="{Binding Subordinates}">
            <TextBlock Text="{Binding Path=Title}" />
        </HierarchicalDataTemplate>
    </TreeView.Resources>
</TreeView>

C#

TreeViewWebpages.ItemsSource = from Webpage root in db.Webpages.Include("Subordinates")
                               where root.Dominant == null
                               select root;

结果

网页在TreeView中没有顺序。

问题

如何通过排序属性将TreeView中显示的所有网页进行排序?


更新

这个ValueConverter似乎可以工作(感谢@KP Adrian和@IVerzin)。是否有更好的方法?

XAML

ItemsSource="{Binding Path=Subordinates, Converter={local:SortConverter}}"

C#

[ValueConversion(typeof(EntityCollection<Webpage>), typeof(EntityCollection<Webpage>))]
public class SortConverter : MarkupExtension, IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return ((EntityCollection<Webpage>)value).OrderBy(o => o.Sort);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return null;
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        return this;
    }
}

1
如果您想对顶级和下级页面进行排序,请使用值转换器:https://dev59.com/K2025IYBdhLWcg3w6aYX - Adrian
1
是的,EntityCollection<T>没有实现IList接口,但您可以将值转换为EntityCollection<WebPage>实例,并在其上调用ToList()方法。-- System.Collections.IList collection = (value as EntityCollection<WegPage>).ToList(); - Adrian
请注意,只有在您拥有一个单一的HierarchicalDataTemplate时,此方法才能有效运行。如果您有多个由DataType属性选择的HierarchicalDataTemplate,使用此方法将对列表进行多次排序,可能会导致速度变慢。我还没有找到解决此问题的方法。 - Etienne
1个回答

0
假设您的Sort属性是一个字符串或整数,用于在运行时确定顺序,您可以在表达式中添加一个orderby部分。
TreeViewWebpages.ItemsSource = from Webpage root in db.Webpages.Include("Subordinates")
                           where root.Dominant == null
                           orderby root.Sort
                           select root;

这不会对下属进行排序。也不会对下属的下属进行排序。 - Zack Peterson
1
你没有提到你想在所有层级上进行排序。我建议采用我上面评论中提到的值转换器解决方案。 - Adrian

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接