本实例实现了对复杂属性MyPerson的状态管理
1、要想实现对MyPerson的状态管理,首先此类要实现IStateManager接口,
其中void IStateManager.LoadViewState(object state)实现对上次保存的视图状态的加载。
而 object IStateManager.SaveViewState()保存本次视图状态。
此两个方法实现的是完全相反的操作,如下类中代码所示。
2、控件类可以是继承自Control,也可以是继承自WebControl
并且要重写控件生命周期中会触发的
protected override void LoadViewState(object savedState)
protected override object SaveViewState()
在这两个方法中分别来调用MyPerson类中的
void IStateManager.LoadViewState(object state)
object IStateManager.SaveViewState()
否则MyPerson类中的以上两个方法,永远不会被执行。
[DefaultProperty("Text")]
[ToolboxData("<{0}:PersonViewState runat=server></{0}:PersonViewState>")]
public class PersonViewState : WebControl
{
private MyPerson myPerson;
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
[NotifyParentProperty(true)]
[PersistenceMode(PersistenceMode.Attribute)]
[DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
public MyPerson MyPerson
{
get
{
if (myPerson == null)
myPerson = new MyPerson();
if (IsTrackingViewState)
((IStateManager)myPerson).TrackViewState();
return myPerson;
}
}
protected override void LoadViewState(object savedState)
{
Pair pair = (Pair)savedState;
base.LoadViewState(pair.First);
((IStateManager)myPerson).LoadViewState(pair.Second);
}
protected override object SaveViewState()
{
Pair pair = new Pair();
pair.First = base.SaveViewState();
pair.Second = ((IStateManager)myPerson).SaveViewState();
return pair;
}
protected override void RenderContents(HtmlTextWriter output)
{
string msg = "我的名字是:"+MyPerson.MyName+" 我的年龄是:"+MyPerson.MyAge;
output.Write("应用视图保存信息:"+msg);
}
}
[TypeConverter(typeof(ExpandableObjectConverter))]
public class MyPerson:IStateManager
{
private string myName;
[NotifyParentProperty(true)]
public string MyName
{
get { return myName; }
set { myName = value; }
}
private string myAge;
[NotifyParentProperty(true)]
public string MyAge
{
get { return myAge; }
set { myAge = value; }
}
#region IStateManager 成员
private bool _IsTrackingViewState = true;
bool IStateManager.IsTrackingViewState
{
get
{
return _IsTrackingViewState;
}
}
void IStateManager.LoadViewState(object state)
{
if (state == null)
return;
object[] myState = (object[])state;
myName = myState[0].ToString();
myAge = myState[1].ToString();
}
object IStateManager.SaveViewState()
{
object[] state = new object[2];
state[0] = myName;
state[1] = myAge;
return state;
}
void IStateManager.TrackViewState()
{
this._IsTrackingViewState = true;
}
#endregion
}