开发者

Stretching columns to fill all available space of DataGrid

开发者 https://www.devze.com 2023-03-24 01:04 出处:网络
Is it possible to stretch columns or the last column to fill all the available space of the data grid?

Is it possible to stretch columns or the last column to fill all the available space of the data grid?

<DataGrid Grid.Row="0" AutoGenerateCo开发者_高级运维lumns="True" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Name="dataGrid1"   ItemsSource="{Binding Customers}" />

My columns are Auto generated.


Yes, I think you are looking for the AutoSizeMode property.

int n = grid.Columns.Count;
grid.Columns[n].AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;

Edit: Try setting the width to "*" as seen below. You'll have to do this in the code if your columns are auto-generated.

<DataGrid>
  <DataGrid.Columns>
    <DataGridTextColumn Width="Auto" />
    <DataGridTextColumn Width="*" />
  </DataGrid.Columns>
</DataGrid>


Since the vast majority of the answers I've found on this topic deal with XAML, here is a C# solution to set all columns to fill the available space in the datagrid.

    foreach (var column in this.datagrid.Columns)
    {
        column.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
    }


Try this approach guys, I wrote it this morning, robust and reliable and allows for percentage based width columns taking all available space. https://stackoverflow.com/a/10526024/41211


DataGrid.Columns[x].Width = DataGridLength.Auto;


If you want to set all column widths to auto except the last column, which should fill the remaining space, try the following code:

for (int i = 0; i < grid.Columns.Count; i++)
{
    if (i == grid.Columns.Count - 1)
    {
        grid.Columns[i].Width = new DataGridLength(1, DataGridLengthUnitType.Star);
    }
    else
    {
        grid.Columns[i].Width = new DataGridLength(1, DataGridLengthUnitType.Auto); 
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消