GridView
データ列の1つがタイプであるデータを表示するためにを使用していますDateTimeOffset
。ユーザーのタイムゾーンで日付と時刻を表示するには、ユーザーのタイムゾーン設定をユーザーのプロファイル(プロパティ値キー "TimezoneOffset")に保存し、日付と時刻をフォーマットするときにアクセスする必要があります。
templatefieldを使用する場合は、次のように記述する必要があります。
<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
ますが、テーブルセルに部分的なビューをレンダリングしたいと思います。それは可能ですか?