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

后端 未结 6 1542
执笔经年
执笔经年 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:28

    I might be a bit late, but you can try my code from this question. I extended original grid and added method for the last column stretching:

    private void StretchLastColumnToTheBorder()
    {
        if (ViewPortWidth.HasValue)
        {
            var widthSum = 0d;
            for (int i = 0; i < Columns.Count; i++)
            {
                if (i == Columns.Count - 1 && ViewPortWidth > widthSum + Columns[i].MinWidth)
                {
                    var newWidth = Math.Floor(ViewPortWidth.Value - widthSum);
                    Columns[i].Width = new DataGridLength(newWidth, DataGridLengthUnitType.Pixel);
                    return;
                }
                widthSum += Columns[i].ActualWidth;
            }
        }
    }
    

    where ViewPortWidth is:

    public double? ViewPortWidth 
    { 
        get 
        {
            return FindChild(this, "PART_ColumnHeadersPresenter")?.ActualWidth;
        } 
    }
    

    So, you have to find the visual child (answer from here) of type DataGridColumnHeadersPresenter, which has the width of the viewport and calculate the width of the last column. To do it automatically, you can fire this method on LayoutUpdated event. Additionally, you can add a DependencyProperty, indicating, whether automatical stretching of the last column should be performed.

提交回复
热议问题