一種有效的向導實現方式
在軟件開發中,對于需要比較復雜,需要多步完成的操作,我們一般采用向導的方式來提供用戶界面。向導設計本身并不困難,但如果要做到通用性強,模塊間盡量低耦合,我們還是得動一下腦筋的。下面介紹一下我的實現方式。
典型的向導界面,主界面上一般包含兩個區域,一是選項區域,二是按鈕區域,包含上一步,下一步,取消等按鈕。向導執行后,每一步該做什么,如果通過條件判斷來進行,顯然會非常麻煩。理想的做法是,上一步的代碼為:
GoLast();
下一步的代碼為:
GoNext();
那怎么做到這一點呢?
首先概念上,我們明確,向導由若干步組成,每一步可以由一個UserControl來表示,執行到該步時,只是創建一個該控件的實例,并顯示在向導主界面的選項區域而已,這一點是不難做到的。那么現在問題的關鍵就是將這些步串聯起來,能夠做到自動的運行。這個任務可以分散到每一步的控件中去,也就是說,每一步應當知道它的上一步是什么,下一步它該做什么,這一點在邏輯上應當是沒有疑慮的。所以,我設計了一個接口IWizardStep,代碼如下:
{
Control NextStepControl
{
get;
}
Control LastStepControl
{
get;set;
}
void BeforeGoNext();
}
其中, NextStepControl表示下一步的控件,如果是最后一步,則應為null,;LastStepControl表示上一步控件,如果是第一步,則該值應null 。BeforeGoNext用于在執行下一步時,做一些選項的應用等預處理工作。每一步的控件只要實現了該接口,向導中的各個步驟就有次序的連接在一起了。
有了上面的這些工作,我們只需要再設計一個用來供主界面調用的外觀類,向導就可以很好的運行了。

public class WizardFacade
{
private System.Windows.Forms.Control m_ParentControl;
private System.Windows.Forms.Control m_CurrentControl;
public WizardFacade(Control parentControl)
{
m_ParentControl =parentControl;
EntranceControl ctl = new EntranceControl()
SetCurrentControl(selctl);
}
/// <summary>
/// 將某一個控件設為當前控件,并顯示出來
/// </summary>
/// <param name="subControl"></param>
private void SetCurrentControl(Control subControl)
{
if (m_CurrentControl != null)
{
(subControl as IWizardStep).Chart = (m_CurrentControl as IWizardStep).Chart;
(subControl as IWizardStep).LastStepControl = m_CurrentControl;
}
subControl.Parent = m_ParentControl;
subControl.Location = new System.Drawing.Point(0,0);
subControl.BringToFront();
subControl.Visible = true;
m_CurrentControl = subControl;
}
/// <summary>
/// 執行下一步
/// </summary>
public void GoNext()
{
(m_CurrentControl as IWizardStep).BeforeGoNext();
if ((m_CurrentControl as IWizardStep).NextStepControl != null)
{
SetCurrentControl((m_CurrentControl as IWizardStep).NextStepControl);
}
}
/// <summary>
/// 執行上一步
/// </summary>
public void GoLast()
{
if ((m_CurrentControl as IWizardStep).LastStepControl != null)
SetCurrentControl((m_CurrentControl as IWizardStep).LastStepControl);
}
/// <summary>
/// 獲取當前正在顯示的控件
/// </summary>
/// <returns></returns>
public Control CurrentStepControl
{
get
{
return m_CurrentControl;
}
}

} 需要注意的是,在構造函數中,有一個EntranceControl的變量,是入口控件,也就是向導的第一步要顯示的控件。在外觀類中明確該控件,在職現分配上應當也是符合邏輯的。
做完了這些,我們的向導主界面就非常簡單了,只需要創建一個WizardFacade對象實例,然后調用相應的方法就可以了。
實踐證明,上述思路簡單,清晰,實用,稍作擴展,可以實現更強大的功能,或者定制你業務中所需要的功能。

浙公網安備 33010602011771號