Model-View-Presenter and Passive View

Model-View-Presenter is the oldest of the patterns a WinForms application uses, and Passive View is its strictest form: the form holds no decisions at all. It reads its controls and writes its controls, raises an event when the user does something, and the presenter decides. Everything a test wants to know is then in a class with no System.Windows.Forms in it.

The interface the form implements

The presenter talks to the form through an interface, and the interface is written from the presenter's side: it names the values the presenter reads, the values it writes and the actions it listens for. Nothing else of the form is visible.

internal interface ILoginView { string UserName { get; } string Password { get; } string ErrorText { set; } string Greeting { set; } void ResetFields(); event EventHandler? SignInRequested; event EventHandler? ClearRequested; }

Three decisions are in those lines. The commands are events, not methods: the view raises SignInRequested when its button is clicked, and the presenter subscribes to it once, in its constructor. The text values are read-only properties, because the presenter reads them but never sets them. The messages are write-only, because the presenter writes them and never reads them back. The one method, ResetFields, exists because the Clear command has to empty the text boxes, and only the view can do that.

The interface is written for the presenter, not for the form. A form has dozens of public members and a hundred properties per control; the presenter sees eight.

The presenter

The presenter is a plain class. It is given the view and the service it needs, subscribes to the two events, and holds the three decisions of the screen:

internal interface IAuthService { bool SignIn(string user, string password); } internal sealed class LoginPresenter { private readonly ILoginView _view; private readonly IAuthService _auth; public LoginPresenter(ILoginView view, IAuthService auth) { _view = view; _auth = auth; view.SignInRequested += OnSignIn; view.ClearRequested += OnClear; } private void OnSignIn(object? sender, EventArgs e) { if (_view.UserName.Length == 0 || _view.Password.Length == 0) { _view.ErrorText = "Both fields are required."; return; } if (!_auth.SignIn(_view.UserName, _view.Password)) { _view.ErrorText = "Wrong user name or password."; return; } _view.ErrorText = string.Empty; _view.Greeting = $"Welcome, {_view.UserName}."; } private void OnClear(object? sender, EventArgs e) { _view.ErrorText = string.Empty; _view.Greeting = string.Empty; _view.ResetFields(); } }

The order of the checks is a decision of the presenter, not of the form: a missing field is reported before the credentials are sent anywhere. The authentication is behind IAuthService for the same reason the view is behind an interface: the presenter must not know whether the answer comes from a database, a web call or a dictionary. Lesson 057 calls this constructor injection.

Note what is absent. There is no MessageBox, because a presenter cannot block on a dialog and a test cannot close one. There is no Text assignment to a control, because there are no controls. And there is no Application.Run, because the presenter exists before the message loop and after it.

The form

The form implements the interface, creates the controls and hands itself to the presenter. This is the whole program, built and not run:

using System; using System.Drawing; using System.Windows.Forms; internal static class Program { [STAThread] private static void Main() { ApplicationConfiguration.Initialize(); Application.Run(new LoginForm()); } } internal interface ILoginView { string UserName { get; } string Password { get; } string ErrorText { set; } string Greeting { set; } void ResetFields(); event EventHandler? SignInRequested; event EventHandler? ClearRequested; } internal interface IAuthService { bool SignIn(string user, string password); } internal sealed class DemoAuth : IAuthService { public bool SignIn(string user, string password) => user == "ada" && password == "secret"; } internal sealed class LoginPresenter { private readonly ILoginView _view; private readonly IAuthService _auth; public LoginPresenter(ILoginView view, IAuthService auth) { _view = view; _auth = auth; view.SignInRequested += OnSignIn; view.ClearRequested += OnClear; } private void OnSignIn(object? sender, EventArgs e) { if (_view.UserName.Length == 0 || _view.Password.Length == 0) { _view.ErrorText = "Both fields are required."; return; } if (!_auth.SignIn(_view.UserName, _view.Password)) { _view.ErrorText = "Wrong user name or password."; return; } _view.ErrorText = string.Empty; _view.Greeting = $"Welcome, {_view.UserName}."; } private void OnClear(object? sender, EventArgs e) { _view.ErrorText = string.Empty; _view.Greeting = string.Empty; _view.ResetFields(); } } internal sealed class LoginForm : Form, ILoginView { private readonly TextBox _user = new() { Location = new Point(110, 18), Width = 220 }; private readonly TextBox _password = new() { Location = new Point(110, 50), Width = 220, UseSystemPasswordChar = true }; private readonly Label _error = new() { Location = new Point(16, 86), AutoSize = true, ForeColor = Color.Firebrick }; private readonly Label _greeting = new() { Location = new Point(16, 110), AutoSize = true }; public LoginForm() { Text = "Sign in"; ClientSize = new Size(360, 150); var signIn = new Button { Text = "&Sign in", Location = new Point(110, 114), Size = new Size(100, 27) }; var clear = new Button { Text = "&Clear", Location = new Point(218, 114), Size = new Size(100, 27) }; signIn.Click += (sender, e) => SignInRequested?.Invoke(this, EventArgs.Empty); clear.Click += (sender, e) => ClearRequested?.Invoke(this, EventArgs.Empty); Controls.Add(new Label { Text = "&User name:", AutoSize = true, Location = new Point(16, 22) }); Controls.Add(new Label { Text = "&Password:", AutoSize = true, Location = new Point(16, 54) }); Controls.Add(_user); Controls.Add(_password); Controls.Add(signIn); Controls.Add(clear); Controls.Add(_error); Controls.Add(_greeting); AcceptButton = signIn; CancelButton = clear; _presenter = new LoginPresenter(this, new DemoAuth()); } private readonly LoginPresenter _presenter; string ILoginView.UserName => _user.Text; string ILoginView.Password => _password.Text; string ILoginView.ErrorText { set => _error.Text = value; } string ILoginView.Greeting { set => _greeting.Text = value; } void ILoginView.ResetFields() { _user.Clear(); _password.Clear(); } public event EventHandler? SignInRequested; public event EventHandler? ClearRequested; }

dotnet build app.csproj

Build succeeded.
    0 Warning(s)
    0 Error(s)

The listing is built and not run. The interface members are implemented explicitly, with string ILoginView.UserName rather than public string UserName, and that is not a style choice. A form is designer-serialisable: the WinForms analyzer expects a public property of a form to say how the designer should save it. Written the obvious way, with two public write-only properties, the build stopped at:

Program.cs(125,19): error WFO1000: Property 'Greeting' does not configure the code serialization for its property content (https://aka.ms/winforms-warnings/wfo1000)
Program.cs(120,19): error WFO1000: Property 'ErrorText' does not configure the code serialization for its property content (https://aka.ms/winforms-warnings/wfo1000)
Build FAILED.
    0 Warning(s)
    2 Error(s)

There are two clean ways out. Explicit interface implementation keeps the members out of the form's public surface, which is exactly what the presenter wants, and no attribute is needed. The other is [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] on the property, which keeps it public and tells the designer to ignore it. The course uses the first, because the form has no reason to publish those members anyway.

The constructor creates the presenter last, after the controls exist, because the presenter may read the view immediately. The presenter field is kept even though nothing else reads it: the two events of the form call into it, and its lifetime is the form's. The form raises the two events with this as the sender, which is where sender comes from in the presenter's handlers.

One click, step by step

user presses the button Button.Click a control event, raised by the message loop LoginForm lambda raises SignInRequested LoginPresenter.OnSignIn reads UserName and Password through ILoginView IAuthService.SignIn the decision, with no UI in it LoginPresenter writes ErrorText or Greeting LoginForm property setter shows the label

Every arrow is a method call on an interface or on a delegate, so every arrow can be followed in a debugger and replaced in a test. The form is a participant only at the two ends.

The presenter in a program that runs

The same interface, service and presenter, with a fake view instead of a form. The fake stores the two messages and hands the presenter the values a user would type; the program drives three attempts and prints what the view received. It was built and run in the container:

using System; using System.Collections.Generic; Console.WriteLine("three sign-in attempts against one presenter"); var view = new FakeLoginView(); var presenter = new LoginPresenter(view, new DemoAuth()); Console.WriteLine("-- submit with both fields empty"); view.Submit(); Console.WriteLine($"error: {view.ErrorText}"); Console.WriteLine($"greeting: '{view.Greeting}'"); Console.WriteLine("-- submit with a wrong password"); view.UserName = "ada"; view.Password = "guess"; view.Submit(); Console.WriteLine($"error: {view.ErrorText}"); Console.WriteLine("-- submit with the right password"); view.Password = "secret"; view.Submit(); Console.WriteLine($"error: '{view.ErrorText}'"); Console.WriteLine($"greeting: {view.Greeting}"); Console.WriteLine("-- clear"); view.Clear(); Console.WriteLine($"user after clear: '{view.UserName}', password after clear: '{view.Password}'"); internal interface ILoginView { string UserName { get; } string Password { get; } string ErrorText { set; } string Greeting { set; } void ResetFields(); event EventHandler? SignInRequested; event EventHandler? ClearRequested; } internal interface IAuthService { bool SignIn(string user, string password); } internal sealed class DemoAuth : IAuthService { public bool SignIn(string user, string password) => user == "ada" && password == "secret"; } internal sealed class LoginPresenter { private readonly ILoginView _view; private readonly IAuthService _auth; public LoginPresenter(ILoginView view, IAuthService auth) { _view = view; _auth = auth; view.SignInRequested += OnSignIn; view.ClearRequested += OnClear; } private void OnSignIn(object? sender, EventArgs e) { if (_view.UserName.Length == 0 || _view.Password.Length == 0) { _view.ErrorText = "Both fields are required."; return; } if (!_auth.SignIn(_view.UserName, _view.Password)) { _view.ErrorText = "Wrong user name or password."; return; } _view.ErrorText = string.Empty; _view.Greeting = $"Welcome, {_view.UserName}."; } private void OnClear(object? sender, EventArgs e) { _view.ErrorText = string.Empty; _view.Greeting = string.Empty; _view.ResetFields(); } } internal sealed class FakeLoginView : ILoginView { private string _user = string.Empty; private string _password = string.Empty; public string UserName { get => _user; set => _user = value; } public string Password { get => _password; set => _password = value; } public string ErrorText { get; set; } = string.Empty; public string Greeting { get; set; } = string.Empty; public void ResetFields() { _user = string.Empty; _password = string.Empty; } public void Submit() => SignInRequested?.Invoke(this, EventArgs.Empty); public void Clear() => ClearRequested?.Invoke(this, EventArgs.Empty); public event EventHandler? SignInRequested; public event EventHandler? ClearRequested; }

dotnet run

three sign-in attempts against one presenter
-- submit with both fields empty
error: Both fields are required.
greeting: ''
-- submit with a wrong password
error: Wrong user name or password.
-- submit with the right password
error: ''
greeting: Welcome, ada.
-- clear
user after clear: '', password after clear: ''

The output is the real run. Three attempts passed through one presenter and one fake view, and the messages show the three branches: both fields empty, the service refusing, and the success that clears the error and writes the greeting. The Clear command emptied the fields through ResetFields, which is how a presenter asks the view to do something no property can express.

The using System.Collections.Generic; line is a leftover of the eventual test list and does not change the program; the interfaces and the classes that follow the top-level statements are ordinary types of the same file.

Exercises

  1. Add a UserNameChanged event to the interface and a rule in the presenter that enables the sign-in button only when both fields have text.
  2. Replace DemoAuth with a service that fails with an exception, catch it in the presenter and show a third error message.
  3. Explain what a test would have to do to drive the form version with public properties, and why the explicit version removes that work.

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does the view hold in Passive View?

    Answer

    Controls and the values the user sees, and no decisions

    Every decision is in the presenter; the form only moves values.

  2. How does the presenter learn that the user pressed the button?

    Answer

    It subscribes to an event the view interface declares

    SignInRequested is part of the interface, so a fake view can raise it too.

  3. Why are ErrorText and Greeting write-only in the interface?

    Answer

    The presenter writes them and never reads them back

    The interface carries exactly what the presenter needs.

  4. What is IAuthService for?

    Answer

    It keeps the authentication answer replaceable and the presenter free of a database

    The presenter depends on the interface, and a test passes a fake.

  5. Why does the presenter check for empty fields before calling the service?

    Answer

    A missing field is reported without a round trip, and the order is a presenter decision

    The order of the checks is part of the screen behaviour.

  6. What is wrong with a public write-only property on a Form?

    Answer

    The WinForms analyzer reports WFO1000 because the designer cannot serialise it

    The real build printed two WFO1000 errors for the obvious version.

  7. How is that error fixed in this lesson?

    Answer

    The members are implemented explicitly, so they are not public on the form

    Explicit implementation keeps them off the form's designer-visible surface.

  8. Why is the presenter created in the form constructor, after the controls?

    Answer

    Because it may read the view at once, so the controls must already exist

    The constructor is the composition point of the screen.

  9. What does the presenter return from OnSignIn?

    Answer

    Nothing: it writes through the view interface

    The signature is EventHandler, and the results travel through the view.

  10. Which type does the view raise as the sender of SignInRequested?

    Answer

    The form itself, with this

    The presenter does not use it, but it is the form that raised the event.

Every listing on this page was built with the .NET SDK 10.0.303 for net10.0-windows against the targeting pack Microsoft.WindowsDesktop.App.Ref 10.0.15 from the offline feed, in a Docker container on Alpine Linux 3.24.3 (x86_64). The programs were built, not run on Linux: WinForms needs Windows. The logic that draws nothing was also run headless on the same machine, and its output is the run output printed below each of those programs.

Article author: Arthur Isaev