WPF Reflections

Oct 4 2007   1:11PM GMT

Sorting listview

Mark Shurmer Profile: MarkWPF


ListView (and the default GridView view) is a great bare bones control for us to add extra functionality – though sorting out of the box would have been handy.

On the face of it, sorting is easy – you handle the click of the header and call Sort on the collection being bound to using the property of the header just clicked. What could be hard about that?

Welllll, there are two problems.

Firstly, you would like to make the sorting process generic rather than either repeating code for each header for each grid
Secondly, you need to know which property to actually sort on and which direction. The reason that you don’t always know the property is due to the fact that the property may be in some arbitary point inside a template defined for the column.

Attached properties are the answer to both these problems, as well as a custom GridViewColumn child class.

For problem one, define an attached property to add sorting functionality and then add to the listview definition , like so:

<ListView Name="lvItems" gu:IsGridSortable="True"

Then to solve problem two, use the derived GridViewColumn class like so:
<gu:SortableGridViewColumn Header="Bid tick" CellTemplate="{StaticResource xxx}" SortPropertyName="BidTick" />
The SortProperty property enables you to specify the property that needs to be sorted very easily
Where gu is a xmlns definition to point to your namespace where your new attached property class lives.
Luckily , for you and me, someone has kindly created just such classes, just check out Joel Rummerman’s blog:

You will see on his blog that if you define two styles with keys HeaderTemplateArrowDown and HeaderTemplateArrowUp then that style will be shown in the header as well. So if they are triangles, the header will show them, which is great.

For the listview sorting itself, take a look at the attached property implementation by Mike Brown, at his blog:

 Comment on this Post

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: