MudBlazor DataGrid实现DateTime实际值与显示值分离并支持排序
解决方案
要实现DateTime类型字段按「22 Nov 2012」格式显示且保留原始类型用于排序,可通过以下两种方式基于MudBlazor的PropertyColumn或TemplateColumn实现:
方案一:利用PropertyColumn的CellFormatter属性
直接在渲染列时,针对DateTime/Nullable
@using System.Globalization @foreach (var column in ColumnDefinitions) { if (column.IsTemplateColumn) { <TemplateColumn Title="@column.Title" Filterable="@column.Filterable" Sortable="@column.Sortable"> @column.CellTemplate </TemplateColumn> } else { var isDateTimeType = column.PropertyType == typeof(DateTime) || column.PropertyType == typeof(DateTime?); <PropertyColumn Property="@column.PropertyExpression" Title="@column.Title" Filterable="@column.Filterable" Sortable="@column.Sortable" CellFormatter="@(isDateTimeType ? (Func<object, string>)(value => value is DateTime date ? date.ToString("dd MMM yyyy", CultureInfo.InvariantCulture) : value is DateTime? nullableDate && nullableDate.HasValue ? nullableDate.Value.ToString("dd MMM yyyy", CultureInfo.InvariantCulture) : string.Empty) : null)" /> } }
CultureInfo.InvariantCulture确保月份缩写为英文格式,避免因系统区域设置导致显示差异- 原始DateTime值会被MudBlazor用于排序逻辑,无需额外处理
方案二:在ColumnDefinition初始化时自动生成DateTime模板列
将格式化逻辑封装到列定义中,创建DateTime类型列时自动生成CellTemplate,渲染代码更简洁:
修改ColumnDefinition构造函数
using System.Globalization; using System.Linq.Expressions; public class ColumnDefinition<TItem> { public string Title { get; set; } public Expression<Func<TItem, object>> PropertyExpression { get; set; } public Type PropertyType { get; set; } public bool Filterable { get; set; } public bool Sortable { get; set; } public RenderFragment<MudBlazor.CellContext<TItem>> CellTemplate { get; set; } public bool IsTemplateColumn => CellTemplate != null; public ColumnDefinition(string title, Expression<Func<TItem, object>> propertyExpression, Type propertyType, bool filterable = true, bool sortable = true) { Title = title; PropertyExpression = propertyExpression; PropertyType = propertyType; Filterable = filterable; Sortable = sortable; // 自动为DateTime类型生成格式化模板 if (propertyType == typeof(DateTime) || propertyType == typeof(DateTime?)) { CellTemplate = context => { var value = PropertyExpression.Compile()(context.Item); var formattedDate = value switch { DateTime date => date.ToString("dd MMM yyyy", CultureInfo.InvariantCulture), DateTime? nullableDate when nullableDate.HasValue => nullableDate.Value.ToString("dd MMM yyyy", CultureInfo.InvariantCulture), _ => string.Empty }; return builder => builder.AddContent(0, formattedDate); }; } } }
渲染代码(无需额外修改)
@foreach (var column in ColumnDefinitions) { if (column.IsTemplateColumn) { <TemplateColumn Title="@column.Title" Filterable="@column.Filterable" Sortable="@column.Sortable"> @column.CellTemplate </TemplateColumn> } else { <PropertyColumn Property="@column.PropertyExpression" Title="@column.Title" Filterable="@column.Filterable" Sortable="@column.Sortable" /> } }
两种方案均能满足需求:方案一适合快速修改渲染逻辑,方案二更适合将格式化规则统一封装到列定义中。
内容的提问来源于stack exchange,提问作者apanay22
相关产品推荐
相关产品推荐

