Question

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

enter image description here

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

Was it helpful?

Solution

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;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top