Click here to Skip to main content
15,891,184 members
Articles / Web Development / ASP.NET

Model View Presenter via .NET

Rate me:
Please Sign up or sign in to vote.
4.14/5 (24 votes)
10 Oct 2009CPOL7 min read 82K   1.9K   79  
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.
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)


Written By
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.

Comments and Discussions