在HierarchicalDataTemplate中排序不起作用

时间:2017-03-09 04:18:37

标签: wpf vb.net treeview

我的WPF / VB Treeview运行得很好,然后我尝试添加实时排序,并且每个人都在南方。现在,当我运行我的应用程序时,TreeView控件中没有任何显示。这就是我的所作所为:

添加了此转换器:

Public Class CollectionViewSorter
Implements IValueConverter

Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert
    Dim collection As System.Collections.IList = TryCast(value, System.Collections.IList)
    Dim view As New ListCollectionView(collection)
    Dim sort As New SortDescription(parameter.ToString(), ListSortDirection.Ascending)
    view.SortDescriptions.Add(sort)
    Return view
End Function
Public Function ConvertBack(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
    Return Nothing
End Function
End Class

在Window.Resources中我有这个:

<CollectionViewSource
    x:Key="cvs"
    IsLiveSortingRequested="True">
</CollectionViewSource>
<local:CollectionViewSorter x:Key="Sorter" />

和此:

<TreeView.ItemTemplate>
<HierarchicalDataTemplate
        ItemsSource="{Binding Path=ChildNodes, Source={StaticResource cvs}, Converter={StaticResource Sorter}, ConverterParameter=Name}">
    <TextBlock Text="{Binding Path=Name}" />
</HierarchicalDataTemplate>

最后,我将代码隐藏中的CollectionViewSource.Source定义为:

Dim cvs As CollectionViewSource = CType(TryFindResource("cvs"), CollectionViewSource)
cvs.Source = Nodes

以上是什么问题?

编辑: 根据我在下面的评论,我删除了转换器的内容,现在就是这样:

Public Function Convert(value As Object, targetType As Type, parameter As Object, culture As CultureInfo) As Object Implements IValueConverter.Convert
    Dim collection As IList = TryCast(value, IList)
    Return collection
End Function

并且TreeView仍为空。因此,我的结论是转换器是问题的根源,但我不知道如何修复它。

1 个答案:

答案 0 :(得分:0)

假设Nodes是属性。

将您的来源绑定在XAML中,如下所示:

<CollectionViewSource
            x:Key="cvs"
            Source="{Binding Nodes}"
            IsLiveSortingRequested="True"/>

删除这两行:

Dim cvs As CollectionViewSource = CType(TryFindResource("cvs"), CollectionViewSource)
cvs.Source = Nodes

转换器在c#

   public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        if (value == null) return null;

        ICollectionView view = (ICollectionView) value ; 
        view.SortDescriptions.Add(new SortDescription(parameter.ToString(), ListSortDirection.Ascending));
        return view;
    }

我查了一下,你的代码很好。