Wednesday, April 4, 2012

DataGrid Frustration

I'm Back
First a brief explanation regarding my lack of posting over the past couple of years.  In the Spring of 2010 I was laid off from the company I had worked at for almost 10 years.  I managed to get a job fairly quickly, but it didn't involve any C#.NET.  Now a prototype application I have been designing using Excel and VBA has outgrown that platform and I'm porting it to C#.NET.  I hauled my library of C#, WPF and Entity Framework books out of storage and dusted the cobwebs off my understanding.  I have to say this blog proved invaluable to me in retracing my educational steps (sort if like a dear-diary  for my brain) and getting me back in gear.  So I'm going to continue to chronicle my frustrations, discoveries and missteps out of a renewed sense of selfishness and Amnesiphobia.

A Default-Sorted DataGrid
Using T4 code templates I have implemented a method for all of my EF Entities that delivers a CollectionView with a default SortDescription that I define as a Static property in each entity's partial class file (outside of the T4 template).  This works great for ListBox controls, but when it came to the DataGrid it started giving me issues with regards to sorting.

The DataGrid worked fine on the initial ItemSource binding but as soon as you changed it (by navigating to another parent object) the default sorting disappeared.  Turns out the DataGrid implements the following method:


This method (for whatever reason) strips off your CollectionView's SortDescriptions.  Arrgh!  This post shows a workaround involving defining your own DataGrid class that inherits from the DataGrid and simply overrides this Dependency Property callback.  Now my default sorts work perfectly.  Here's the workaround: