DataGrid Setting the size of columns in code behin

2019-07-15 14:51发布

问题:

I am auto generating my columns

<DataGrid Grid.Row="0" AutoGenerateColumns="True" VerticalAlignment="Stretch" HorizontalAlignment="Stretch" Name="dataGrid1"   ItemsSource="{Binding Customers}" />

Now I want to set the size of each column in the code behind , to do something like this

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

I just want to attach to each column "Auto" , and to the last "*" , and everything in code behind.

Thanks.

回答1:

Try something like this

int lastColumn= dataGrid.Columns.Count -1;
dataGrid.Columns[lastColumn].Width = new DataGridLength(0, DataGridLengthUnitType.Star);

for(int i = 0 ; i < dataGrid.Columns.Count -1; i ++)
    dataGrid.Columns[i].Width = new DataGridLength(0, DataGridLengthUnitType.Auto);

As you are AutoGeneratingColumns you can handle the AutoGeneratedColumns event of dataGrid and put code above inside that event