views:

527

answers:

2

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.

  1. 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
  2. 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
  3. 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?

A: 

Hi skylap, I have also faced the same problem as you stated. I searched a bit in the internet, and probably find a solution. The solution actually works for me properly. Set the * value from C# code. Here is the code snippet,

dg.Coulmns[0].Width = new DataGridLength(1.0, DatGridLengthUnitType.Star);

It will set the 0th column's width to . Don't forget to remove the Width="1*" from the XAML page.

Enjoy Guru.

Subha Basu