We pay for user submitted tutorials and articles that we publish. Anyone can send in a contributionLearn More
Often we want to display a list of elements and allow the user to sort them in various ways. There are many ways to do it and I wanted to show you how to use a SortDescription Object. What is a SortDescription object you ask? It receives two parameters in its constructor: the first is a string that represents the property name we want to sort by, and the second is a ListSortDirecton which is an Enum that has 2 Values: Ascending and Descending and I bet you know what they mean…
What you need to do is add this object to the items of a collection, and they will be sorted. Easy right?
Let’s assume we have an object that has a property which is called Duration, and we wanted to make the list of objects ascend by the Duration property.
we would write something like this:
SortDescription desc = new SortDescription("Duration" , ListSortDirection.Descending); m_TasksListbox.Items.SortDescriptions.Add(desc);
Another nice thing is the fact that we can sort by two properties, if we add two SortDescription objects, the list will be sorted by the first and then by the second.
SortDescription desc = new SortDescription("Duration", ListSortDirection.Descending);
m_TasksListbox.Items.SortDescriptions.Add(desc); desc = new SortDescription("Status", ListSortDirection.Descending); m_TasksListbox.Items.SortDescriptions.Add(desc);
Another thing to notice is that we are not performing these actions on the data. In the example above m_TasksListbox is a Listbox, so you don’t care about the data type you have in your DataContext, you are performing the sorting on the view.
Don’t forget to clean the SortDescription objects before you change the sorting of the view.
Use the following line:
Subscribe to our feed and get the complete code sample for this article
, comment if you need help.
Tags :BindingCollectionItemsItemsControlListBoxListView TreeViewSortSortDescriptonSorting
Copyright © 2012 Dev102.com
Breeze : Designed by Amit Raz and Nitzan Kupererd