Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DataGrid Setting the size of columns in code behind when the columns are auto generated

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.

like image 353
Night Walker Avatar asked Dec 21 '22 10:12

Night Walker


1 Answers

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

like image 146
Haris Hasan Avatar answered Dec 24 '22 02:12

Haris Hasan