简体   繁体   中英

Wpf Datagrid: resize column from code

in WPF i have a datagrid, populated with an ItemSource:

myDataGrid.ItemsSource = myData;

I'd like to set the width of the column 0 to a specific width. If i type this code:

var tmp = myDataGrid.Columns;

why tmp is null? How can i resize a specific column from code behind?

I put an image example: the datasource is "newListModel" that has 4 rows and each item has 3 columns. If i try to get the columns 0 i get an exception outofrange

在此处输入图片说明

I have only this in XAML for the definition of the datagrid:

<DataGrid x:Name="dataGridListe" HorizontalAlignment="Left" Margin="10,303,0,0" VerticalAlignment="Top" Height="155" Width="676" CanUserAddRows="False" MouseDoubleClick="dataGridListe_MouseDoubleClick"/>

Thanks

You have to define the columns in the XAML also set the AutoGenerateColumns to be False.

<DataGrid x:Name="dataGridListe" VerticalAlignment="Top" AutoGenerateColumns="False" >
        <DataGrid.Columns>                
            <DataGridTextColumn Header="YourProperty1" Binding="{Binding Path=YourProperty1}"/>
            <DataGridTextColumn Header="YourProperty2" Binding="{Binding Path=YourProperty2}"/>
            ....
           </DataGrid.Columns>
 </DataGrid>

Then, You need to specify the index of the column

DataGridColumn column = dataGridListe.Columns[0];
column.Width = 200;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM