If you’ve used
the the Silverlight 2 DataGrid, you’ve no doubt seen this:
I really hate when this happens! I’ve seen several forum discussions where folks were looking to get rid of this nastiness, so I know I’m not the only one losing sleep over it. I haven’t come across a solution in anything I’ve seen and so now that I have one, I thought I’d share it.
I ran into this a few weeks back and tried most of the obvious things with defining the DataGridColumns myself rather than auto-generating them. In these defined DataGridColumns, I tried setting the Width of the last column to “*” just like you would a standard Grid.ColumnDefinition if you wanted to have it take up the remainder of the space. This did nothing more than invite my buddy, AG_E_PARSER_BAD_PROPERTY, to show up…again. It appears that star-sizing isn’t yet implemented for DataGridColumn derivatives.
This morning I was finally able to grab a few minutes to dive into DataGrid and find out what I could do about this. I decided to create an ExtendedDataGrid and add a LastColumnFill DependencyProperty similar to way the DockPanel has a LastChildFill. Most of the work is happening in this method which is called if the LastColumnFill is true:
private void AdjustLastColumnWidth(Size finalSize)
{
// get the Vertical ScrollBar
ScrollBar scrollBar = this.GetTemplateChild(“VerticalScrollbar”) as ScrollBar;
// compute the width to allow for the scrollbar based on its visibility.
double scrollBarWidthAllowance = (scrollBar != null && scrollBar.Visibility == Visibility.Visible) ? scrollBar.ActualWidth + 2 : 2;
// compute the width of all the columns excluding the last one
var widthOfAllButLastColumn = this.Columns
.TakeWhile(c => c != Columns.Last() &&
c.Visibility == Visibility.Visible)
.Sum(c => c.ActualWidth);
// set the last column width
this.Columns.Last().Width = new DataGridLength(finalSize.Width – widthOfAllButLastColumn – scrollBarWidthAllowance);
}
This is the result:
Much better! The live demo shows it with and without a vertical scrollbar. Note that it also handles auto-generated DataGridColumns if that’s your thang.
Here’s the live demo.
Here’s the code.