Joan Venge Joan Venge - 1 year ago 216
C# Question

How to sort TreeView items using SortDescriptions in Xaml?

I have a list of

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

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

I am trying to sort them first by
, then by

Any ideas?

EDIT: I added this code:


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


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

Answer Source

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

<TreeView Name="treeCategories" Margin="5" ItemsSource="{Binding Source={StaticResource SortedLayers}}">
    <HierarchicalDataTemplate ItemsSource="{Binding Effects, Converter={StaticResource myConverter}, ConverterParameter=EffectName}">
        <TextBlock Text="{Binding Path=LayerName}" />
                <TextBlock Text="{Binding Path=EffectName}" />

and converter:

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

        return view;

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        return null;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download