0
votes

I try to resize the columns of my DataGrid that the columns just take enough space they needed.

Can't upload an image of what I want it seems.

But for example:

Header      |Header         |
Content     |MoreContent    |

How can I make it:

Header |Header2    |
Content|MoreContent|

Tried this in the xaml file:

ColumnWidth="*"

And this:

MyDataGrid.AutoGeneratedColumns += MyDataGrid_AutoGeneratedColumns;

private void MyDataGrid_AutoGeneratedColumns(object sender, EventArgs e)
    {
        foreach (var oColumn in OgonePaymentInfoDataGrid.Columns)
        {
            // This is how to set the width to *
            oColumn.Width = new DataGridLength(1.0, DataGridLengthUnitType.Star);
        }
    }

This is how I fill my DataGrid:

MyDataGrid.ItemsSource = items;
2
The columns should be auto-sized by default. Are you setting the width explicitly somewhere?mm8
@mm8 yes this did the trick removing ColumnWidth="*"user7998549

2 Answers

1
votes

ColumnWidth="*" will stretch all DataGrid columns equally. you can use

<DataGrid ColumnWidth="{x:Static DataGridLength.SizeToCells}">

</DataGrid>

without additional event handlers for AutoGeneratedColumns event.

ColumnWidth property has type DataGridLength, and SizeToCells is one of possible values, which are defined as static properties.

0
votes

The columns are auto-sized by default. Make sure that you don't explicitly set the Width somewhere, i.e. remove ColumnWidth="*" and it should work just fine.