Click here to Skip to main content
15,885,244 members
Articles / Desktop Programming / WPF

Presentation Model (MVVM) Good Practices

Rate me:
Please Sign up or sign in to vote.
4.81/5 (13 votes)
11 May 2010CPOL16 min read 67.8K   944   76  
Showing some good practices that can be applied to the Presentation Model/MVVM pattern.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Input;
using PresentationModelBase;
using System.Reflection;

namespace App.Configuration
{
    class MethodCallCommand : ICommand
    {
        public MethodCallCommand(PresentationModel target) 
        {
            _target = target;
        }

        PresentationModel _target;

        #region ICommand Members

        public bool CanExecute(object parameter)
        {
            return true;
        }

        public event EventHandler CanExecuteChanged;

        public void Execute(object parameter)
        {
            MethodInfo currentMethod = _target.GetType().GetMethod(parameter.ToString(), BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
            if (currentMethod == null)
                throw new ArgumentException("Cannot find this method");

            ParameterInfo[] parameters = currentMethod.GetParameters();
            if (parameters != null && parameters.Length > 0)
                throw new ArgumentException("Methods called by this command must have no parameters");

            Type returnType = currentMethod.ReturnType;
            if (returnType != typeof(void))
                throw new ArgumentException("Methods called by this command must return void");

            _target.InvokeMethod(currentMethod);
        }

        protected virtual void Execute(MethodInfo mi) 
        {
            mi.Invoke(_target, null);
        }

        #endregion
    }
}

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
Brazil Brazil
Software developer specialized in the .NET framework

Comments and Discussions