#983 – Using a CollectionViewSource to Sort Items in a ListBox
January 9, 2014 5 Comments
You can sort items within a ListBox using a CollectionViewSource, which is a wrapper around a view of a collection. The CollectionViewSource provides support for sorting, filtering and grouping items in the underlying collection. It provides a mechanism for configuring the view from XAML.
In the example below, we define a CollectionViewSource that wraps a collection of Actor objects and specifies a property to sort on (the actor’s last name). Our ListBox then binds to the CollectionViewSource rather than to the collection.
<Window.Resources> <CollectionViewSource x:Key="cvsActors" Source="{Binding ActorList}" > <CollectionViewSource.SortDescriptions> <scm:SortDescription PropertyName="LastName" /> </CollectionViewSource.SortDescriptions> </CollectionViewSource> </Window.Resources> <StackPanel> <ListBox Name="lbActors" Margin="15" Width="200" Height="190" ItemsSource="{Binding Source={StaticResource cvsActors}}"/> </StackPanel>
The Actor objects in our ListBox are now sorted by their LastName. (LastName is a property of the Actor object).
Pingback: Dew Drop – January 9, 2014 (#1698) | Morning Dew
Pingback: #984 – Grouping Items in a ListBox with a CollectionViewSouorce | 2,000 Things You Should Know About WPF
Pingback: #986 – Filtering a ListBox Using a CollectionViewSource | 2,000 Things You Should Know About WPF
Pingback: #987 – CollectionViewSource Updates on Refresh or Change to Collection | 2,000 Things You Should Know About WPF
Pingback: #988 – Enabling Live Sorting in a CollectionViewSource | 2,000 Things You Should Know About WPF