How can I sort a ListBox using only XAML and no code-behind? How can I sort a ListBox using only XAML and no code-behind? wpf wpf

How can I sort a ListBox using only XAML and no code-behind?


Use a CollectionViewSource:

<CollectionViewSource x:Key="SortedItems" Source="{Binding CollectionOfStrings}"    xmlns:scm="clr-namespace:System.ComponentModel;assembly=Win‌​dowsBase">    <CollectionViewSource.SortDescriptions>        <scm:SortDescription PropertyName="SomePropertyOnYourItems"/>    </CollectionViewSource.SortDescriptions></CollectionViewSource><ListBox ItemsSource="{Binding Source={StaticResource SortedItems}}"/>

You might want to wrap your strings in a custom VM class so you can more easily apply sorting behavior.


If attached property qualifies as no code the following can be used:

public static class Sort{    public static readonly DependencyProperty DirectionProperty = DependencyProperty.RegisterAttached(        "Direction",        typeof(ListSortDirection?),        typeof(Sort),        new PropertyMetadata(            default(ListSortDirection?),            OnDirectionChanged));    [AttachedPropertyBrowsableForType(typeof(ItemsControl))]    public static ListSortDirection? GetDirection(ItemsControl element)    {        return (ListSortDirection)element.GetValue(DirectionProperty);    }    public static void SetDirection(ItemsControl element, ListSortDirection? value)    {        element.SetValue(DirectionProperty, value);    }    private static void OnDirectionChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)    {        if (d is ItemsControl { Items: { } items })        {            if (e.NewValue is ListSortDirection direction)            {                items.SortDescriptions.Add(new SortDescription(string.Empty, direction));            }            else if (e.OldValue is ListSortDirection old &&                     items.SortDescriptions.FirstOrDefault(x => x.Direction == old) is { } oldDescription)            {                items.SortDescriptions.Remove(oldDescription);            }        }    }}

Then in xaml:

<ListBox local:Sort.Direction="Ascending"         ... />

Another attached property that is of type SortDescription probably makes sense in many cases.