You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MudBlazor DataGrid动态高度调整:消除底部多余空白

解决MudDataGrid动态高度问题:数据不足时消除底部空白

问题场景

使用MudDataGrid时,已基于屏幕尺寸设置固定高度,当每页行数超出该高度时会显示滚动条,但当记录数少于设定高度/每页行数(或多页场景的最后一页)时,DataGrid底部记录与分页器之间会出现多余空白。需要实现:数据高度超出设定值时保持固定高度(显示滚动),数据高度不足时自动收缩高度消除空白。

解决方案思路

通过动态计算当前页面的实际数据总行数,结合行高、表头高度算出当前数据区域的总高度,与预设的固定高度对比,动态切换MudDataGrid的Height属性:

  • 当计算出的实际数据高度 ≥ 预设固定高度时,使用固定高度(保持滚动条)
  • 当实际数据高度 < 预设固定高度时,设置Height="auto"(自动收缩)

具体实现步骤

  1. 绑定当前页码:给MudDataGrid添加@bind-CurrentPage="CurrentPage",用于跟踪当前所在页面
  2. 计算当前页实际行数:根据总数据量、每页行数、当前页码,算出当前页显示的记录数
  3. 动态计算高度:结合MudBlazor默认行高(52px)、表头高度(56px),计算当前数据区域的总高度,与预设固定高度比较后决定Height值

完整代码示例

@inject IScreenSizeService Service

@code {
    private List<Element> Elements = ElementData.SampleData;
    private int rowsperpage = 10;
    private int CurrentPage = 1;
    // 预设固定高度(基于屏幕尺寸)
    private string FixedHeight => $"{Service.Height - 100}px";
    // 默认行高(可根据自定义样式调整)
    private const int RowHeight = 52;
    // 默认表头高度
    private const int HeaderHeight = 56;

    // 动态计算DataGrid的高度
    private string DynamicHeight
    {
        get
        {
            // 计算当前页的实际行数
            int totalItems = Elements.Count;
            int itemsOnCurrentPage = Math.Min(rowsperpage, totalItems - (CurrentPage - 1) * rowsperpage);
            
            // 计算当前数据区域的总高度:表头高度 + 行高度*行数
            int actualHeight = HeaderHeight + itemsOnCurrentPage * RowHeight;
            // 把预设固定高度转成数值
            if (int.TryParse(FixedHeight.Replace("px", ""), out int fixedHeightValue))
            {
                // 实际高度小于固定高度则用auto,否则用固定高度
                return actualHeight < fixedHeightValue ? "auto" : FixedHeight;
            }
            // 解析失败默认用固定高度
            return FixedHeight;
        }
    }
}

<MudDataGrid Items="@Elements" 
             Filterable="true" 
             FilterCaseSensitivity="DataGridFilterCaseSensitivity.CaseInsensitive" 
             RowsPerPage="@rowsperpage" 
             Context="context" 
             FixedHeader="true" 
             Height="@DynamicHeight"
             @bind-CurrentPage="CurrentPage">
    <Columns>
        <PropertyColumn Property="x => x.Number" Title="Nr" />
        <PropertyColumn Property="x => x.Sign" />
        <PropertyColumn Property="x => x.Name" />
        <PropertyColumn Property="x => x.Position" />
        <PropertyColumn Property="x => x.Molar" Title="Molar mass" />
    </Columns>
    <NoRecordsContent>
        <MudText>No matching records found</MudText>
    </NoRecordsContent>
</MudDataGrid>

注意事项

  • 如果自定义了行高(比如通过CSS修改.mud-data-grid-row的高度),需要同步调整代码中的RowHeight数值
  • 若使用了分组、行展开等功能,需要额外计算这些元素的高度,调整actualHeight的计算逻辑
  • 当屏幕尺寸变化时,FixedHeight会自动更新,DynamicHeight也会重新计算,保持适配

内容的提问来源于stack exchange,提问作者Sapri s

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.28 00:53:14