How can I sort a ListBox using only XAML and no code-behind?
31,697
Use a CollectionViewSource
:
<CollectionViewSource x:Key="SortedItems" Source="{Binding CollectionOfStrings}"
xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase">
<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.
Author by
Eben Geer
Updated on July 09, 2022Comments
-
Eben Geer almost 2 years
I need to sort the strings in a
ListBox
, but it is bound to the view model by another component via theDataContext
. So I can't directly instantiate the view model in XAML, as in this example, which uses theObjectDataProvider
.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.
-
Eben Geer almost 15 yearsThanks, Kent! Binding the Source attribute on a CollectionViewSource was the missing link for me. I appreciate it. In this case, I didn't want a custom VM class, so I just left off the PropertyName attribute, which apparently works for string collections just fine.
-
Eben Geer almost 15 yearsAlso, to any onlookers out there, the SortDescription tag takes a Direction attribute.
-
Ingó Vals over 13 yearsWhat if the ListBox is a part of a DataTemplate representing a property of a object that is a list of items. Can't I do the sorting inside the ListBox somehow?
-
Ingó Vals almost 13 yearsCan you tell us where the smc namespace looks like. I'm not succesfully finding SortDescription using Xaml.
-
Shadow The Kid Wizard almost 13 yearsComment by franssu:
scm
includes the "System.ComponentModel" namespace from the WindowsBase assembly.(xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase")
-
Konstantin Salavatov over 10 yearsfor Silverlight xmlns:scm="="clr-namespace:System.ComponentModel;assembly=System.Windows"
-
RobM over 4 yearsThere seems to be some hidden characters in the code snippet. Copying it to notepad++ shows this for example 'Win??dowsBase' I had the SortOnDescription issue also. The characters don't show up in blend. Retyping 'WindowsBase' fixed it for me. I would edit the snippet but it complains that I need to edit more than 6 characters.