3
votes

Assuming a resizable grid with 2 columns placed inside a DockPanel (such that it fills all the space in it).

When the columns have width specified as "1*", each column gets half the space initially. Extending column1 shrinks column2 by the same amount. As a result, the horizontal scrollbar does not show up. (It also means that I cannot extend both the columns i.e. the combined width is greater than the visible area.)

When the columns have width specified as "Auto" (default), each column is auto-sized to max(cell content, column header). Extra space may be left over at the right past the last column. You can extend each column without shrinking the others.. the horizontal scrollbar is shown if necessary.

How can I configure the wpf datagrid to equally divide the available space initally AND extending any column should not shrink any other column i.e. horizontal scrollbar should come up as if they were configured for Auto ?

2

2 Answers

1
votes

This might help::

dataGrid.Loaded+=new RoutedEventHandler(dataGrid_Loaded);

void dataGrid_Loaded(object sender, EventArgs e)
{
    DataGrid dataGrid = sender as DataGrid;
    double width = dataGrid.ActualWidth;
    int count = dataGrid.Columns.Count;
    foreach (DataGridColumn col in dataGrid.Columns)
    {
        col.Width = width / count;
    }
}
1
votes

I think you need to set a static width on each column for this to work. I'd suggest using a converter which takes your DataGrid's width and divides it by the # of columns you have

I have a fairly simple MathConverter on my blog that I use for all mathematical conversions. It's fairly easy to extend into an IMultiValueConverter as well if you need to. The end result will look something like this:

<DataGridTextColumn Width="{Binding ElementName=MyDataGrid, Path=ActualWidth,
    Converter={StaticResource MathConverter}, ConverterParameter=@VALUE/2}" ... />

You might even be able to apply the Width in a implicit Style in <DataGrid.Resources> if you don't want to specify it on each column

<DataGrid.Resources>
    <Style TargetType="{x:Type DataGridColumn}">
        <Setter Property="Width" 
                Value="{Binding ElementName=MyDataGrid, 
                    Path=ActualWidth, 
                    Converter={StaticResource MathConverter}, 
                    ConverterParameter=@VALUE/2}" />
    </Style>
</DataGrid.Resources>