Thursday, March 12, 2009

Silverlight Data Grid & Stretching Columns

In Silverlight data grid, often we run into situations where there is a lot of empty space after the last column. What we want instead is that the last column should stretch to the very end of the data grid.


Here is small function that I wrote which will take care of that. It's not that elegant, but will get the job done.


void ResizeColumns()
{
int NumColumns = DataGridEntities.Columns.Count;
if (NumColumns > 0)
{
double DataGridWidth = DataGridEntities.ActualWidth;
double TotalColumnsWidth = 0;
for (int ii = 0; ii < NumColumns - 1; ii++)
{
TotalColumnsWidth += DataGridEntities.Columns[ii].ActualWidth;
}
double LastColumnWidth = DataGridEntities.Columns[NumColumns - 1].ActualWidth;
double EmptySpace = DataGridWidth - (TotalColumnsWidth + LastColumnWidth);
if (EmptySpace > 0)
{
DataGridEntities.Columns[NumColumns - 1].Width = new DataGridLength(LastColumnWidth + EmptySpace);
}
}
}










Basically after databinding is done on the data grid, we have data grid's and it's columns actual . What we do is add up all column's actual width, find the difference between the two and add it to the last column's width.


I know it's not elegant but will get the job done.


Comments, Suggestions!!!


Gaurav

No comments: