2011-10-02 28 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( );'... –

相关问题