MVP:演示者如何访问视图属性?

时间:2011-10-02 12:25:03

标签: c# .net winforms 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属性。它只能由演示者访问。那可能吗?我做的事情完全不正确吗?请指教!

1 个答案:

答案 0 :(得分: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();

他们无法访问这些属性。