我正在使用 aGridView
来显示其中一个数据列具有 type 的数据DateTimeOffset
。为了在用户的时区显示日期和时间,我将用户的时区偏好保存到他或她的个人资料(属性值键“TimezoneOffset”),并且在格式化日期和时间时需要访问它。
如果我要使用模板字段,那么我需要编写:
<abbr class="datetimeoffset">
<%#
((DateTimeOffset)Eval("CreatedDate"))
.ToOffset(new TimeSpan(-((Int32)Profile.GetPropertyValue("TimezoneOffset"))
.ToRepresentativeInRange(-12, 24), 0, 0)).ToString("f") %>
</abbr>
这太复杂且不可重用。
我尝试向TimeSpan
代码隐藏添加一个属性(至少将其移出数据绑定表达式),但显然视图的代码隐藏属性在<%# ... %>
.
因此,我认为我需要编写一个自定义DataControlField
格式以在用户的时区中格式化日期和时间。
我开始了:
public class DateTimeOffsetField : DataControlField
{
private TimeSpan userOffsetTimeSpan;
protected override DataControlField CreateField()
{
return new DateTimeOffsetField();
}
protected override void CopyProperties(DataControlField newField)
{
base.CopyProperties(newField);
((DateTimeOffsetField)newField).userOffsetTimeSpan = userOffsetTimeSpan;
}
public override bool Initialize(bool sortingEnabled, System.Web.UI.Control control)
{
bool ret = base.Initialize(sortingEnabled, control);
int timezoneOffset = ((Int32)HttpContext.Current.Profile.GetPropertyValue("TimezoneOffset")).ToRepresentativeInRange(-12, 24);
userOffsetTimeSpan = new TimeSpan(-timezoneOffset, 0, 0);
return ret;
}
}
但现在我被困住了。如何输出<abbr class="datetimeoffset"><%# ((DateTimeOffset)Eval("CreatedDate")).ToOffset(userOffsetTimeSpan).ToString("f") %></abbr>
每个单元格的 HTML?
编辑:我一直在阅读一篇题为“前沿:自定义数据控制字段”的文章。到目前为止,我已经添加:
public override void InitializeCell(DataControlFieldCell cell, DataControlCellType cellType, DataControlRowState rowState, int rowIndex)
{
base.InitializeCell(cell, cellType, rowState, rowIndex);
if (cellType == DataControlCellType.DataCell)
{
InitializeDataCell(cell, rowState, rowIndex);
}
}
protected virtual void InitializeDataCell(DataControlFieldCell cell, DataControlRowState rowState, int rowIndex)
{
System.Web.UI.Control control = cell;
if (control != null && Visible)
{
control.DataBinding += new EventHandler(OnBindingField);
}
}
protected virtual void OnBindingField(object sender, EventArgs e)
{
var target = (System.Web.UI.Control)sender;
if (target is TableCell)
{
TableCell tc = (TableCell)target;
}
}
但是虽然文章设置了实例的Text
属性,但TableCell
我想将部分视图呈现到表格单元格中。那可能吗?