WPF DataGrid window resize does not resize DataGridColumns
- by skylap
I have a WPF DataGrid (from the WPFToolkit package) like the following in my application.
<Controls:DataGrid>
<Controls:DataGrid.Columns>
<Controls:DataGridTextColumn Width="1*" Binding="{Binding Path=Column1}" Header="Column 1" />
<Controls:DataGridTextColumn Width="1*" Binding="{Binding Path=Column2}" Header="Column 2" />
<Controls:DataGridTextColumn Width="1*" Binding="{Binding Path=Column3}" Header="Column 3" />
</Controls:DataGrid.Columns>
</Controls:DataGrid>
The column width should be automatically adjusted such that all three columns fill the width of the grid, so I set Width="1*" on every column. I encountered two problems with this approach.
When the ItemsSource of the DataGrid is null or an empty List, the columns won't size to fit the width of the grid but have a fixed width of about 20 pixel. Please see the following picture: http://img169.imageshack.us/img169/3139/initialcolumnwidth.png
When I maximize the application window, the columns won't adapt their size but keep their initial size. See the following picture: http://img88.imageshack.us/img88/9362/columnwidthaftermaximiz.png
When I resize the application window with the mouse, the columns won't resize.
I was able to solve problem #3 by deriving a sub class from DataGrid and override the DataGrid's OnRenderSizeChanged method as follows.
protected override void OnRenderSizeChanged(SizeChangedInfo sizeInfo)
{
base.OnRenderSizeChanged(sizeInfo);
foreach (var column in Columns)
{
var tmp = column.GetValue(DataGridColumn.WidthProperty);
column.ClearValue(DataGridColumn.WidthProperty);
column.SetValue(DataGridColumn.WidthProperty, tmp);
}
}
Unfortunately this does not solve problems #1 and #2. How can I get rid of them?