6.2.4 實現自定義類型視圖狀態
前面對視圖狀態的概念和原理已經說得比較清楚了,這一節就以一個實例說明ViewState工作原理。建立一個Web自定義控件ViewStateControl,該控件繼承於WebControl或Control,代碼如下:
/// <summary>
/// 獲得本書更多內容,請看:
/// http://blog.csdn.net/ChengKing/archive/2008/08/18/2792440.aspx
/// </summary>
[ToolboxData("<{0}:ViewStateControl runat=server></{0}:ViewStateControl>")]
public class ViewStateControl : WebControl
{
}
由於WebControl是繼承於Control基類的,因此該控件已經具備控件生命周期在視圖階段執行方法LoadViewState和SaveViewState的能力。在控件中增加三個不同類型的屬性,如下所示:
/// <summary>
/// 獲得本書更多內容,請看:
/// http://blog.csdn.net/ChengKing/archive/2008/08/18/2792440.aspx
/// </summary>
private string _text;
[Bindable(true)]
[DefaultValue("")]
[Localizable(true)]
[Category("測試視圖狀態")]
[Description("沒有使用視圖狀態存儲")]
public string Text_NoViewState
{
get
{
return _text;
}
set
{
this._text = value;
}
}
[Bindable(true)]
[DefaultValue("")]
[Localizable(true)]
[Category("測試視圖狀態")]
[Description("使用ViewState屬性來存儲數據此屬性")]
public string Text_ViewState
{
get
{
String s = (String)ViewState["Text_ViewState"];
return ((s == null) ? String.Empty : s);
}
set
{
ViewState["Text_ViewState"] = value;
}
}
private FaceStyle _faceStyle;
[PersistenceMode(PersistenceMode.InnerProperty)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
[NotifyParentProperty(true)]
[Category("測試視圖狀態")]
[Description("自定義視圖狀態(實現IStateManager接口)存儲此屬性")]
public FaceStyle FaceStyle
{
get
{
if (_faceStyle == null)
{
_faceStyle = new FaceStyle();
}
if (IsTrackingViewState)
{
((IStateManager)_faceStyle).TrackViewState();
}
return _faceStyle;
}
}