Sorting View Model Items Using CollectionViewSource

If you create a Windows Phone 7 data bound application using the template, the item list is not sorted. I found that the simplest way to do that is to use System.Windows.Data.CollectionViewSource. The example on MSDN is perhaps not so helpful, since a static resources are used. You would typically want to bind to dynamic data. I found the solution in a blog post called Use CollectionViewSource effectively in MVVM applications, but decided to implement it a little different. Here is what I did:

In MainViewModel.cs, I kept the Items property of type ObservableCollection<T> and created a new property called SortedItems of type CollectionViewSource:

public CollectionViewSource SortedItems { get; private set; }

The getter of Items returns the CollectionViewSource Source, and the setter of Items updates the CollectionViewSource Source:

       using AccountCollection = ObservableCollection<Account>;

       public AccountCollection Items
        {
            get { return (AccountCollection)SortedItems.Source; }
            private set
            {
                var items = (AccountCollection)SortedItems.Source;
                items.Clear();
                foreach (var item in value)
                {
                    items.Add(item);
                }
             }
         }

In the MainViewModel constructor, I initialize the CollectionViewSource and tell it to sort ascending on a property called Name:

        public MainViewModel()
        {
            this.SortedItems = new CollectionViewSource();
            this.SortedItems.Source = new AccountCollection();
            this.SortedItems.SortDescriptions.Add(new System.ComponentModel.SortDescription("Name", System.ComponentModel.ListSortDirection.Ascending));
        }

Then I changed the binding in MainPage.xaml like this:

<ListBox x:Name="MainListBox" Margin="0,0,-12,0" ItemsSource="{Binding SortedItems.View}">

#yam

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s