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

半腔热情 提交于 2020-01-05 02:11:17

问题


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



来源:https://stackoverflow.com/questions/6881684/datagrid-setting-the-size-of-columns-in-code-behind-when-the-columns-are-auto-ge

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!