【问题标题】:Stretch last DataGrid column拉伸最后一个 DataGrid 列
【发布时间】:2021-02-03 04:53:32
【问题描述】:

我正在尝试实现一种自动拉伸最后一列的方法。我创建了新类FancyDataGrid 并定义了一个名为StretchLastColumnPropertyDependencyProperty。如果为真,LayoutUpdated 事件会触发以下方法:

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

虽然此方法适用于较小的DataGrid,但如果此网格足够高以具有垂直滚动条,则效果不佳。在这种情况下,最后一列变得太宽了,差异不仅仅是滚动条​​的宽度。

我的方法有什么问题?如何在考虑滚动条宽度的情况下调整最后一列的宽度?

编辑: 将最后一列宽度设置为星号仅在最初有效。调整列大小后,将不再调整其宽度。

【问题讨论】:

  • @Sinatr 根据 OP,这个问题也没有答案
  • 什么意思?它有 5 个答案。
  • 原帖:“我将其中一个答案标记为解决方案,但实际上由于 WPF 设计,它不是解决方案……”所有答案都是将宽度设置为星号,这只有效第一次,直到调整此列的大小。
  • “直到调整此列的大小” - 你能提供更多细节吗?为什么允许调整列的大小?如果用户调整最后一列的大小,实际会发生什么?还是其他栏目?

标签: c# wpf


【解决方案1】:

我查看了DataGrid 模板的层次结构并注意到,内部ColumnHeadersPresenter 的宽度正好是视口的宽度(DataGrid 宽度减去左右边框减去垂直滚动条宽度)。所以使用this question的方法你可以找到这个元素并得到它的宽度:

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

然后用它来计算所需的宽度:

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;
        }
    }
}

请注意,如果您拉伸左侧列,最后一列将在开始向右移动(移出视口)之前缩小到其MinWidth,从而出现水平滚动条。

【讨论】:

    猜你喜欢
    • 2018-12-04
    • 2014-03-12
    • 1970-01-01
    • 2018-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-26
    • 2011-01-26
    相关资源
    最近更新 更多