Antoine V
Antoine V

Reputation: 7204

WPF last column to stretch through DataGrid

Is there any way to force the last column to stretch through the width of DataGrid WPF?

Because in some situation when the width of DataGrid is larger than the width of all columns cumulated, DataGrid behaves like containing a last empty column .

<DataGrid Grid.Row="1" ItemsSource="{Binding Params}"  Width="Auto"
         AutoGenerateColumns="True" HeadersVisibility="None">
</DataGrid>

public List<KeyValuePair<string,string>> Params { get; set; }

DataGrid with "an empty column"

Upvotes: 1

Views: 1253

Answers (2)

Pseudonymos
Pseudonymos

Reputation: 19

If you are using a SfDataGrid from syncfusion, the member to use is ColumnSizer (and not Width).

Code behind:

    private void DataGrid_AutoGeneratingColumn(object sender, AutoGeneratingColumnArgs eventArgs)
    {
        string columnMappingName = eventArgs.Column.MappingName;

        if (columnMappingName == "Name")
        {
            eventArgs.Column.ColumnSizer = GridLengthUnitType.Star;
        }
    }

XAML:

<syncfusion:SfDataGrid AutoGeneratingColumn="DataGrid_AutoGeneratingColumn"/>

Upvotes: 0

mm8
mm8

Reputation: 169270

You could handle the AutoGeneratedColumns event and set the Width of the last column to * programmatically:

private void DataGrid_AutoGeneratedColumns(object sender, EventArgs e)
{
    DataGrid dataGrid = (DataGrid)sender;
    dataGrid.Columns[dataGrid.Columns.Count - 1].Width = new DataGridLength(1, DataGridLengthUnitType.Star);
}

XAML:

<DataGrid Grid.Row="1" ItemsSource="{Binding Params}" 
          Width="Auto" AutoGenerateColumns="True" HeadersVisibility="None"
          AutoGeneratedColumns="DataGrid_AutoGeneratedColumns">
</DataGrid>

Upvotes: 3

Related Questions