简体   繁体   English

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

[英]MVP: How does presenter access view properties?

I will give a full example that compiles: 我将给出一个完整的编译示例:

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);
    }
}

It's a pretty simple application. 这是一个非常简单的应用程序。 It has an MVP user control. 它具有MVP用户控件。 This user control has a public property Param which controls its appearance. 该用户控件具有控制其外观的公共属性Param

My problem is that I want to hide the Checked property from users. 我的问题是我想向用户隐藏Checked属性。 It should be accessible only by the presenter. 它只能由演示者访问。 Is that possible? 那可能吗? Am I doing something completely incorrect? 我做的事情完全不正确吗? Please advise! 请指教!

You can't completely hide it from the end user, and truthfully, you don't need to. 您无法将其完全隐藏给最终用户,实际上,您不需要这样做。 If someone wants to use you user control directly, your control should be dumb enough to just display the properties that are set on it, regardless if they were set through a presenter or not. 如果有人想直接使用您的用户控件,则您的控件应足够笨拙,以仅显示在其上设置的属性,而不管它们是通过演示者设置的。

The best you can do however (if you still insist on hiding those properties from your user), is to implement the IView explicitly: 但是,您可以做的最好的事情(如果您仍然坚持对用户隐藏这些属性),则是明确实现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);
    }

This way, if someone just does: 这样,如果有人这样做:

var ctl = new View();

they won't have access to those properties. 他们将无法访问这些属性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM