Search code examples
c#.netwpfdatagrid

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"


Solution

  • 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>