State的描述和實例
State的作用和對象中的Property作用差不多,用於傳遞對象間的狀態。
1. 創建一個Module,並命名爲SCSF.Sample.StateModel:
圖2.8.1
2. 作用需要傳遞的State需要在SHELL中進行初始化。
protected override void BeforeShellCreated() { base.BeforeShellCreated();
RootWorkItem.State["StateList"] = new List<string>();
} |
並且在Module啓動時在Controller中添加以下代碼給State賦初始值。
public class ModuleController : WorkItemController { 。。。 private void AddViews() { addStateValue(); 。。。 }
private void addStateValue() { List<string> statelist = (List<string>)WorkItem.RootWorkItem.State["StateList"]; statelist.Add("one"); statelist.Add("two"); statelist.Add("three"); statelist.Add("four");
} } |
3. 在View中定義方法操作State的值,並在Presenter類中處理State值的獲取和設置。下面以其中一個視圖的代碼作爲例子,先在視圖otherView中輸入如下代碼:
[SmartPart] public partial class otherView : UserControl, IotherView { 。。。 #region IotherView 成員
public void setStateTxt(string ss) { this.textBox1.Text = ss; }
#endregion
private void button1_Click(object sender, EventArgs e) { _presenter.setStateTxt(); }
private void button2_Click(object sender, EventArgs e) { _presenter.inputStateValue(this.textBox1.Text); } } |
在otherViewPresenter類中輸入如下代碼:
public class otherViewPresenter : Presenter<IotherView> { 。。。 [Microsoft.Practices.CompositeUI.State("StateList")] public List<string> states { set { if (value != null) { states = value; } } get { return (List<string>)WorkItem.RootWorkItem.State["StateList"]; } }
public void setStateTxt() { string st = string.Empty; for (int i = 0; i < states.Count; i++) {
st+= (string)states[i];
} View.setStateTxt(st); }
public void inputStateValue(string ss) { states.Add(ss); } } |
其他兩個視圖也按同樣的方式寫好代碼。
4. 完成後運行。
圖2.8.2
其中點擊getState按鈕會把初始值讀取並放進顯示框中,點擊setState按鈕則可在State值中增加對應信息。
圖2.8.3