Friday, June 26, 2009

WPF: Sorting Sets of Simple Strings

I've been doing a fair bit of WPF coding recently, and it's a compelling experience. The thing is, it isn't easy, and I think that surprises some people. Part of the reason for this is that the documentation still feels incomplete, in that undocumented kind of way. But the other reason is that it forces you to think very abstractly, all the time. If I were to think of a decent analogy, it would be one involving cooking: Coding in most UI toolkits is like cooking with lots of pre-made dishes (pre-cooked noodles, microwave dinners, pasta sauces out of the bottle.) Sure, you can make a decent meal, but the results are pretty predictable and maybe not that satisfying. Coding in WPF is like cooking with real ingredients - it can be challenging, and you can certainly mess up the results, but you can also whip up something fantastic.

That said, I thought I might pass along a tip for something that seems like it should be quite easy, but the documentation makes it unclear. I needed to produce two comboboxes for some UI, both of which contain lists of Strings. For one combobox, I needed a custom sort pattern, and for the second one I needed a straight up sort.
I'm finding that there are a bunch of ways to do this. You can create a List<> object that contains the strings, call Sort() on it, then bind it. However, that might not be an adequate solution since you're re-arranging your internal data and you may want to preserve its original order.
The other way of doing this is to apply a SortDescription to the Items list of your combobox or ListView. A SortDescription is pair consisting of a String which describes the property to sort on, and a sort order (ascending or descending.)
Now here's a little tip I just figured out: Most examples explain how to Sort a list of items that are bound to the control, by specifying the property name of the property to sort the content on.
combobox.Items.SortDescriptions.Add( 
    new SortDescriptions("Content", ListSortDirection.Ascending));
But what if your items don't have a sub-property? You may have guessed the answer, but I am hear to confirm that if you pass an empty string as the first parameter to the SortDescription, then it will apply the SortDirection to the Items themselves:
combobox.Items.SortDescriptions.Add( 
    new SortDescriptions("", ListSortDirection.Ascending));
And voila! For the second combo where I needed a custom sort, I simply did my sort on the items themselves beforehand then added them in the right order.

0 comments:

Post a Comment

  © Blogger templates The Professional Template by Ourblogtemplates.com 2008

Back to TOP