Search code examples
c#.netwinformsmvp

Writing a user interface settings class using MVP pattern


I'm trying to understand the Model-View-Presenter pattern at the moment. Let's say I have a user interface (view) and there are some controls on it. I'd like to give the user the option to save the state of the controls (for example; window size, selected tab, DataGridView column sizes and so on).

Now if I create a "Settings" model, it is going to have properties like "dgvColumnSize1", "WindowsSize" and so on. But then the model knows about the view, and designed specifically for it.

What should I do to decouple them?


Solution

  • The properties are decoupled in the sense that the model is not directly coupled to a specific view, rather to any view that has those properties... but I understand what you mean.

    There are two approaches you can use:

    Opaque State

    The views package their state into an opaque state object that can be stored in the model. The view is then responsible to package and unpackage its state from the state object and change accordingly. Examples of objects that can be used to store properties in an opaque way include dictionaries, ExpandoObject and JSON/XML strings.

    MVP Hierarchies

    The Model-View-X family of architectural patterns can be set in hierarchies where the view of a bottom MV-X is the model of the next in line. Usually two or three chained MV-Xs are needed in the hierarchy:

    An optional bottom MVC to act as the DAL layer, an optional middle MVC to act as the business layer and a set of MVP for the different user/machine interfaces of the application on top.

    The bottom MVC architectures are completely presentation layer agnostic while the top MVP is tailored suited to the presentation layer.

    How does the top MVPs pass along the presentation layers' state to the bottom layers for persistance, you ask? Why using opaque objects of course!

    By the way if this setup sounds like Microsoft's MVVM pattern used in WPF, that's because it is. MVVM is just a slight modification of the MVP pattern if it can be called a different pattern at all.