MudDataGrid固定高度下多余空间去除与动态高度调整方案
MudDataGrid 动态高度适配方案
问题说明
使用MudDataGrid时已配置随屏幕尺寸动态变化的固定高度,当每页行数超出该高度时会自动显示滚动条。但存在以下问题:
- 单页记录数少于高度对应行数时,网格底部与分页器之间出现多余空白
- 多页场景下的最后一页,同样存在上述空白
需求:非最后一页保持固定高度(超出时滚动),最后一页自动适配内容高度(无多余空白)
实现步骤
- 给MudDataGrid添加引用,用于获取过滤后的总条目数和当前页信息
- 编写动态计算高度的方法,判断当前页是否为最后一页,返回对应高度值
- 绑定当前页属性,确保页码切换时自动重新计算高度
完整代码示例
@inject IService Service <MudDataGrid @ref="_dataGrid" Items="@Elements" Filterable="true" FilterCaseSensitivity="DataGridFilterCaseSensitivity.CaseInsensitive" RowsPerPage="@rowsperpage" FixedHeader="true" Height="@GetGridHeight()" @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> @code { private MudDataGrid<Element> _dataGrid; private int _currentPage = 1; private int rowsperpage = 10; private List<Element> Elements = new(); private string GetGridHeight() { // 获取过滤后的总条目数,优先用DataGrid内置的TotalItems(过滤后准确) var totalItems = _dataGrid?.TotalItems ?? Elements.Count; // 计算总页数,无数据时默认1页 var totalPages = totalItems == 0 ? 1 : (int)Math.Ceiling((double)totalItems / rowsperpage); // 最后一页/总条目数不足一页时用auto,否则用固定高度 return _currentPage == totalPages || totalItems <= rowsperpage ? "auto" : $"{Service.Height - 100}px"; } // 数据模型示例 public class Element { public int Number { get; set; } public string Sign { get; set; } public string Name { get; set; } public int Position { get; set; } public double Molar { get; set; } } }
关键细节说明
@ref="_dataGrid":必须添加该引用,才能获取过滤后的真实总条目数(直接用Elements.Count无法处理过滤场景)GetGridHeight():核心逻辑,通过总条目数和每页行数计算总页数,判断当前页是否为最后一页,动态返回高度值@bind-CurrentPage="_currentPage":绑定当前页,确保切换页码时自动触发高度重新计算- 无数据场景处理:当
totalItems为0时,总页数设为1,此时高度为auto,避免空白
内容的提问来源于stack exchange,提问作者Sapri s
相关产品推荐
相关产品推荐

