开发者

MVP: How does presenter access view properties?

开发者 https://www.devze.com 2023-04-09 18:42 出处:网络
I will give a full example that compiles: using System.Windows.Forms; interface IView { string Param { set; }

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. This user control has a public property Param which controls its appearance.

My problem is that I want to hide the Checked property from users. 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:

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号