How to make the last column in WPF datagrid take all the left space, always?

后端 未结 6 1546
执笔经年
执笔经年 2020-12-10 00:50

Standard WPF 4 Datagrid.

Let\' say I have datagrid 200 pixels wide, and 2 columns. I would like the columns take always entire space, meaning if the user resizes the

6条回答
  •  孤街浪徒
    2020-12-10 01:14

    Here's a very simple answer, all performed in code behind. :-) All columns will be auto-sized; the final column will fill all remaining space.

    // build your datasource, e.g. perhaps you have a:
    List people = ...
    
    // create your grid and set the datasource
    var dataGrid = new DataGrid();
    dataGrid.ItemsSource = people;
    
    // set AutoGenerateColumns to false and manually define your columns
    // this is the price for using my solution :-)
    dataGrid.AutoGenerateColumns = false;
    
    // example of creating the columns manually.
    // there are obviously more clever ways to do this 
    var col0 = new DataGridTextColumn();
    col0.Binding = new Binding("LastName");
    var col1 = new DataGridTextColumn();
    col1.Binding = new Binding("FirstName");
    var col2 = new DataGridTextColumn();
    col2.Binding = new Binding("MiddleName");
    dataGrid.Columns.Add(col0);
    dataGrid.Columns.Add(col1);
    dataGrid.Columns.Add(col2);
    
    // Set the width to * for the last column
    col2.Width = new DataGridLength(1, DataGridLengthUnitType.Star);
    
    

提交回复
热议问题