【问题标题】:WPF DataGrid scrollbar appearanceWPF DataGrid 滚动条外观
【发布时间】:2023-03-08 02:33:01
【问题描述】:

我有一个派生自DataGrid 的类,它会延伸最后一列,如果它的右侧有可用空间:

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

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

StretchLastColumnToTheBorder()LayoutUpdated 被触发后被调用。一切正常,除非表格有足够的行来显示垂直滚动条。显然,它不会在 DataGrid 加载后立即出现,导致宽度计算错误。如何检查垂直滚动条是否已初始化?

编辑: Width="Auto" 调整列的大小以适合其最长的单元格。 Width="*" 仅将列的初始宽度设置为拉伸到末尾。但是,如果缩小任何一列,最后一列后面会出现空白。

【问题讨论】:

  • 你想重新发明轮子吗?最后一列的 Width="Auto" 和 Width="*" 有什么问题?
  • 我编辑了我的帖子以明确他们有什么问题。
  • 如何检查垂直滚动条是否已初始化?尝试在可视化树中找到它?
  • @mm8 当然,我可以在可视化树中找到它。但是如何检查,是否应该显示?
  • 如果它在可视化树中,它是可见的(当然取决于Visibility 属性的值)。如果不存在,则没有滚动条。

标签: c# wpf


【解决方案1】:

如果您获得ScrollViewer 对应的DataGrid,则可以检查ComputedVerticalScrollBarVisibility 属性。

【讨论】:

    【解决方案2】:

    Loaded 处理程序中订阅LayoutUpdated 可以解决问题。在这种情况下,IsLoaded 检查也是多余的。所以,有

    public FancyDataGrid() : base()
    {
        Loaded += OnLoaded;
    }
    
    private void OnLoaded(object sender, RoutedEventArgs e)
    {
        LayoutUpdated += OnLayoutUpdated;
    }
    

    而不是

    public FancyDataGrid() : base()
    {
        LayoutUpdated += OnLayoutUpdated;
    }
    

    允许在计算垂直滚动条时访问视口。

    【讨论】:

      猜你喜欢
      • 2011-10-06
      • 1970-01-01
      • 2012-11-17
      • 2011-07-05
      • 1970-01-01
      • 1970-01-01
      • 2023-03-22
      • 2017-07-12
      • 1970-01-01
      相关资源
      最近更新 更多