2011-10-02 66 views
0

我會給一個完整的例子,編譯:MVP:演示者如何訪問視圖屬性?

using System.Windows.Forms; 
interface IView { 
    string Param { set; } 
    bool Checked { set; } 
} 
class View : UserControl, IView { 
    CheckBox checkBox1; 
    Presenter presenter; 
    public string Param { 
     // SKIP THAT: I know I should raise an event here. 
     set { presenter.Param = value; } 
    } 
    public bool Checked { 
     set { checkBox1.Checked = value; } 
    } 
    public View() { 
     presenter = new Presenter(this); 
     checkBox1 = new CheckBox(); 
     Controls.Add(checkBox1); 
    } 
} 
class Presenter { 
    IView view; 
    public string Param { 
     set { view.Checked = value.Length > 5; } 
    } 
    public Presenter(IView view) { 
     this.view = view; 
    } 
} 
class MainClass { 
    static void Main() { 
     var f = new Form(); 
     var v = new View(); 
     v.Param = "long text"; 
     // PROBLEM: I do not want Checked to be accessible. 
     v.Checked = false; 
     f.Controls.Add(v); 
     Application.Run(f); 
    } 
} 

這是一個非常簡單的應用程序。它有一個MVP用戶控件。該用戶控件具有控制其外觀的公共屬性Param

我的問題是,我想隱藏用戶的Checked屬性。它只能由演示者訪問。那可能嗎?我做的事情完全不正確嗎?請指教!

回答

3

您不能將其完全從最終用戶隱藏起來,並且如實地不需要。如果有人想直接使用你的用戶控件,你的控件應該足夠愚蠢,只顯示設置的屬性,無論它們是否通過演示者設置。

最好的,你可以但是你(如果你仍然堅持從用戶隱藏這些屬性),是貫徹落實IView明確:

class View : UserControl, IView { 
    CheckBox checkBox1; 
    Presenter presenter; 
    string IView.Param { 
     // SKIP THAT: I know I should raise an event here. 
     set { presenter.Param = value; } 
    } 
    bool IView.Checked { 
     set { checkBox1.Checked = value; } 
    } 
    public View() { 
     presenter = new Presenter(this); 
     checkBox1 = new CheckBox(); 
     Controls.Add(checkBox1); 
    } 

這樣一來,如果有人只是做:

var ctl = new View(); 

他們將無法訪問這些屬性。

+0

+1表示你不需要打擾。代碼審查應該會發現這種濫用:)但是,如果用戶通過'IView'而不是通過'View'來引用它,這很容易獲得:'IView view = new View( );'... –