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

Eben Geer picture Eben Geer · Aug 15, 2009 · Viewed 30.2k times · Source

I need to sort the strings in a ListBox, but it is bound to the view model by another component via the DataContext. So I can't directly instantiate the view model in XAML, as in this example, which uses the ObjectDataProvider.

In my XAML:

<ListBox ItemsSource="{Binding CollectionOfStrings}" />

In my view model:

public ObservableCollection<string> CollectionOfStrings
{
    get { return collectionOfStrings; }
}

In another component:

view.DataContext = new ViewModel();

There is no code behind! So using purely XAML, how would I sort the items in the ListBox? Again, the XAML doesn't own the instantiation of the view model.

Answer

Kent Boogaart picture Kent Boogaart · Aug 15, 2009

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.