Alex Rivera | Logout

How do you sort a CollectionViewSource by one property, then by another as a tiebreak?

Asked 2013-02-20T23:44:02.983
18

Currently, my CollectionViewSource sorts a collection of items by description. If the description is the same, I want to sort based on ID. How can I specify to sort by description first, then by ID?

I've tried adding a second SortDescription with PropertyName="Id", but that hasn't worked.

 <CollectionViewSource x:Key="Items" Source="{Binding Items}" >
 <CollectionViewSource.SortDescriptions>
 <scm:SortDescription PropertyName="Description"/>
 </CollectionViewSource.SortDescriptions>
 </CollectionViewSource>

EDIT: The ID property was private on the viewmodel. No errors thrown.

Edit
Report

1 Answer

44

I'm not sure why adding the SortDescription for Id does not work as it should work fine.

Like this:

<CollectionViewSource x:Key="Items" Source="{Binding ElementName=UI, Path=Items}" >
    <CollectionViewSource.SortDescriptions>
        <scm:SortDescription PropertyName="Description" />
        <scm:SortDescription PropertyName="Id" />
    </CollectionViewSource.SortDescriptions>
 </CollectionViewSource>

I put together a full example of this working as you want:

Xaml:

<Window x:Class="WpfApplication7.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:scm="clr-namespace:System.ComponentModel;assembly=WindowsBase"
    Title="MainWindow" Height="124" Width="464" Name="UI" >
<Window.Resources>

   <CollectionViewSource x:Key="Items" Source="{Binding ElementName=UI, Path=Items}" >
    <CollectionViewSource.SortDescriptions>
        <scm:SortDescription PropertyName="Description" />
        <scm:SortDescription PropertyName="Id" />
    </CollectionViewSource.SortDescriptions>
   </CollectionViewSource>
</Window.Resources>

<Grid>
    <ListBox ItemsSource="{Binding Source={StaticResource Items}}" />
</Grid>

Code:

public partial class MainWindow : Window
{
    private ObservableCollection<MyObject> myVar = new ObservableCollection<MyObject>();

    public MainWindow()
    { 
        InitializeComponent();
        Items.Add(new MyObject { Description = "Stack", Id = 5 });
        Items.Add(new MyObject { Description = "OverFlow", Id = 1 });
        Items.Add(new MyObject { Description = "StackOverFlow", Id = 2 });
        Items.Add(new MyObject { Description = "Stack", Id = 1 });
        Items.Add(new MyObject { Description 
answered 2013-02-21T00:08:30.260

Your Answer