#983 – Using a CollectionViewSource to Sort Items in a ListBox

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>

983-001
The Actor objects in our ListBox are now sorted by their LastName. (LastName is a property of the Actor object).
983-002

Advertisements

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

5 Responses to #983 – Using a CollectionViewSource to Sort Items in a ListBox

  1. Pingback: Dew Drop – January 9, 2014 (#1698) | Morning Dew

  2. Pingback: #984 – Grouping Items in a ListBox with a CollectionViewSouorce | 2,000 Things You Should Know About WPF

  3. Pingback: #986 – Filtering a ListBox Using a CollectionViewSource | 2,000 Things You Should Know About WPF

  4. Pingback: #987 – CollectionViewSource Updates on Refresh or Change to Collection | 2,000 Things You Should Know About WPF

  5. Pingback: #988 – Enabling Live Sorting in a CollectionViewSource | 2,000 Things You Should Know About WPF

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: