网格聚集
Grid组件为列值提供了基于的内置聚合分组还有一行。
在本文中:
可用的聚合函数
类下有几个可用的聚合函数Telerik.Blazor.GridAggregateType
枚举:
平均
数
马克斯
最小值
总和
的数
聚合可以应用于任何类型的字段。其他聚合只能应用于数值领域(例如,int
,小数
,双
等)。
哪里可以使用聚合
你可以在以下模板中使用聚合:
GroupFooterTemplate
的GridColumn
-当网格分组时,在各自列中呈现的页脚。GroupHeaderTemplate
的GridColumn
-当网格按该列分组时,在各自列中呈现的标题。的价值
上下文中的字段携带当前组值。FooterTemplate
的GridColumn
-整个网格的总行页脚。
如何启用聚合
启用聚合:
- 下
GridAggregates
标记,定义GridAggregate
项来启用您想要使用的每个字段的聚合。 - 如果网格被绑定到动态对象(Expando),设置
FieldType
属性。GridAggregate
标签(它是类型的类型
). - 在支持聚合结果的模板中使用聚合结果
上下文
是强类型的,并携带各自字段中的聚合值。 - 设置网格的
Groupable
财产真正的
.- 如果你只使用
FooterTemplate
S -分组不是必需的。
- 如果你只使用
- 对网格进行分组,以查看对特定于组的模板的影响
例子
在Telerik Blazor网格中使用聚合
启用并使用聚合。要看到完整的效果,分组按一栏-“团队”,然后“活动项目”。 Total: @context.Count employees.
@{ // you can use aggregates for other fields/columns by extracting the desired one by its // field name and aggregate function from the AggregateResults collection // The type of its Value is determined by the type of its field - decimal for the Salary field here decimal salaries = (decimal)context.AggregateResults .FirstOrDefault(r => r.AggregateMethodName == "Sum" && r.Member == "Salary")?.Value; } Total salaries: @salaries.ToString("C0") Team Members: @context.Count @context.Value @* the default text you would get without the template *@ Team size: @context.Count @* you can use a group footer for non-groupable columns as well *@ Total salaries: @context.Sum
Highest: @context.Max @{ Currently active projects: @context.Value //sample of conditional logic in the group header if ((int)context.Value > 3) // in a real case, you may want to ensure type safety and add defensive checks { These people work on too many projects } } @code { public List GridData { get; set; } protected override void OnInitialized() { GridData = new List(); var rand = new Random(); for (int i = 0; i < 15; i++) { Random rnd = new Random(); GridData.Add(new Employee() { EmployeeId = i, Name = "Employee " + i.ToString(), Team = "Team " + i % 3, Salary = rnd.Next(1000, 5000), ActiveProjects = i % 4 == 0 ? 2 : 5 }); } } public class Employee { public int EmployeeId { get; set; } public string Name { get; set; } public string Team { get; set; } public decimal Salary { get; set; } public int ActiveProjects { get; set; } } }
控件对网格进行分组后,上面代码段的结果团队
而且活动项目
列
笔记
您应该只定义您将使用的聚合,以避免在大型数据集上可能明显的不必要计算。
如果尝试使用未定义的聚合,或使用不支持的字段类型的聚合,则将抛出运行时错误。
如果更新模型的字段,则
数据
在视图模型中,聚合将不会自动更新-网格需要首先重新评估数据,因为这是一个昂贵的操作,UI渲染不会触发它。你可以更新数据集合或者从服务中重新获取它(例如在这里,请参阅Create/Update/Delete事件如何重新获取数据)。如果你通过绑定网格
OnRead
事件,一定要设置AggregateResults
在GridReadEventArgs
事件参数对象。否则,Grid将仅从当前页面上的数据计算聚合。
private async Task OnGridRead(GridReadEventArgs args) {DataSourceResult result = AllGridData.ToDataSourceResult(args. request);arg游戏。数据= result.Data; args.Total = result.Total; args.AggregateResults = result.AggregateResults; }