Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

Model View Presenter via .NET

, 10 Oct 2009
An article outlining an implementation of the Model View Presenter pattern in .NET, contrasting it with existing implementations of MVP, MVC, and using co-dependant interfaces to allow for abstract coordination.
ExampleProject.zip
ExampleProject.Contracts
bin
Debug
CobaltSoftware.Foundation.ModelViewPresenter.dll
ExampleProject.Contracts.dll
Properties
ExampleProject.Model
bin
Debug
CobaltSoftware.Foundation.ModelViewPresenter.dll
ExampleProject.Contracts.dll
ExampleProject.Model.dll
Properties
ExampleProject.Presenters
bin
Debug
CobaltSoftware.Foundation.ModelViewPresenter.dll
ExampleProject.Contracts.dll
ExampleProject.Presenters.dll
Properties
ExampleProject.Views
bin
Debug
CobaltSoftware.Foundation.ModelViewPresenter.dll
ExampleProject.Contracts.dll
ExampleProject.Views.dll
Properties
CobaltSoftware.Foundation.ModelViewPresenter
bin
Debug
CobaltSoftware.Foundation.ModelViewPresenter.dll
Core
Properties
Support
ExampleProject.Application
bin
Debug
CobaltSoftware.Foundation.ModelViewPresenter.dll
ExampleProject.Application.exe
ExampleProject.Application.vshost.exe
ExampleProject.Application.vshost.exe.manifest
ExampleProject.Contracts.dll
ExampleProject.Model.dll
ExampleProject.Presenters.dll
ExampleProject.Views.dll
Properties
Settings.settings
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using ExampleProject.Contracts;

namespace ExampleProject.Views
{
    /// <summary>
    ///     The Clock View Control displays timezones and time, and allows
    ///     the user to select a new timezone.
    /// </summary>
    public partial class ClockViewControl : UserControl, IClockView
    {
        public ClockViewControl()
        {
            InitializeComponent();
        }

        #region IClockView Members

        /// <summary>
        ///     Set the time-zones on the display
        /// </summary>
        public IEnumerable<TimeZoneInfo> TimeZones
        {
            set 
            {
                this.Combo_TimeZones.DataSource = value;
                this.Combo_TimeZones.DisplayMember = "DisplayName";
                this.Combo_TimeZones.ValueMember = "DisplayName";
            }
        }

        /// <summary>
        ///     Set the currently displayed time.
        /// </summary>
        public DateTime Time
        {
            set 
            {
                if (LableTime.InvokeRequired)
                    LableTime.Invoke(new Action<Label, String>(UpdateLabel), new Object[] { LableTime, value.ToLongTimeString() });
                else
                    UpdateLabel(LableTime, value.ToLongTimeString());

            }
        }

        /// <summary>
        ///     Selected time-zone
        /// </summary>
        public TimeZoneInfo SelectedTimeZone
        {
            set
            {

                if (LableTime.InvokeRequired)
                    LableTime.Invoke(new Action<ComboBox, TimeZoneInfo>(UpdateComboValue), new Object[] { Combo_TimeZones, value });
                else
                    UpdateComboValue(Combo_TimeZones, value);
            }
        }

        #endregion

        #region Cross-thread invokers

        /// <summary>
        ///     Update a labels value
        /// </summary>
        /// <param name="instance">Label instance</param>
        /// <param name="text">Text</param>
        /// <remarks>Required due to the oddities of WinForms</remarks>
        private void UpdateLabel(Label instance, String text)
        {
            // Validate parameters
            if (instance == null)
                throw new ArgumentNullException("instance");
            if (String.IsNullOrEmpty(text))
                throw new ArgumentNullException("text");

            instance.Text = text;
        }

        /// <summary>
        ///     Update a combo-box value
        /// </summary>
        /// <param name="instance">Combo-box instance</param>
        /// <param name="selection">Selection value</param>
        /// <remarks>Required due to the oddities of WinForms</remarks>
        private void UpdateComboValue(ComboBox instance, Object selection)
        {
            // Validate parameters
            if (instance == null)
                throw new ArgumentNullException("instance");
            if (selection == null)
                throw new ArgumentNullException("selection");

            instance.SelectedItem = selection;
        }

        #endregion

        #region IView<IClockView,IClockPresenter> Members

        private IClockPresenter _Presenter;

        /// <summary>
        ///     Attatch to presenter
        /// </summary>
        /// <param name="presenter">Presenter</param>
        /// <param name="requiresInitialState">Requires initial state push?</param>
        public void AttachToPresenter(IClockPresenter presenter, bool requiresInitialState)
        {
            // Validate argumnets
            if (presenter == null)
                throw new ArgumentNullException("presenter");

            // Detatch from any existing presenter
            DetatchFromPresenter();

            // Set our current presenter
            _Presenter = presenter;

            // Notify the presenter that we're connecting.
            Presenter.ConnectView(this, requiresInitialState);
        }

        /// <summary>
        ///     Detatch from the presenter
        /// </summary>
        public void DetatchFromPresenter()
        {
            lock (this)
            {
                // Disconnnect from presenter if needed.
                if (Presenter != null)
                {
                    Presenter.DisconnectView(this);
                    _Presenter = null;
                }
            }
        }

        /// <summary>
        ///     Current presenter instance
        /// </summary>
        public IClockPresenter Presenter
        {
            get 
            {
                return _Presenter;
            }
        }

        #endregion

        /// <summary>
        ///     When the timezone has changed in the drop-down, raise our time-zone changed
        ///     event.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Combo_TimeZones_SelectionChangeCommitted(object sender, EventArgs e)
        {
            // If we've got a presenter, notify it of the timezone shift.
            if (Presenter != null)
                Presenter.ChangeTimeZone(Combo_TimeZones.SelectedItem as TimeZoneInfo);
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Steven James Gray
Software Developer (Senior) Insurance Industry
United Kingdom United Kingdom
Steve Gray is a Senior Developer at a British insurance company, working on a popular aggregator. When he's not writing ASP .NET, it's because there's SQL or WCF to write instead.

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 10 Oct 2009
Article Copyright 2009 by Steven James Gray
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid