I'm trying to implement a method for automatic stretching of the last column. I created new class FancyDataGrid
and defined a DependencyProperty
called StretchLastColumnProperty
. When it's true, following method gets triggered by LayoutUpdated
event:
private void StretchLastColumnToTheBorder()
{
var widthSum = 0d;
for (int i = 0; i < Columns.Count; i++)
{
widthSum += Columns[i].ActualWidth;
if (i == Columns.Count - 1 && this.ActualWidth > widthSum)
{
var newWidth = Math.Floor(Columns[i].ActualWidth + (this.ActualWidth - widthSum)) -
(this.BorderThickness.Left + this.BorderThickness.Right);
Columns[i].Width = new DataGridLength(newWidth, DataGridLengthUnitType.Pixel);
}
}
}
While this method works for small DataGrid
, it doesn't work well if this grid is high enough to have a vertical scrollbar. In this case last column becomes too wide, and the difference is more than just scrollbar width.
What is wrong with my method? How can I adjust last column width, taking scrollbar width into account?
EDIT: Setting last column width to asterisk only works initially. Once column has been resized, its width will not be adjusted anymore.