Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 348
Eben Geer Avatar asked Aug 14 '09 23:08

Eben Geer


1 Answers

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.

like image 148
Kent Boogaart Avatar answered Sep 22 '22 05:09

Kent Boogaart