The Command Pattern in .NET: Listing 1

Full source code for the MessageBoxCommand

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Input;
using System.ComponentModel;
 
namespace VSMCommandPatternDemo.Commands
{
    public class MessageBoxCommand : ICommand
    {
        private object _receiver;
 
        public MessageBoxCommand()
        {
        }
 
        public MessageBoxCommand(object receiver)
        {
            _receiver = receiver;
 
            if (_receiver as INotifyPropertyChanged != null)
            {
                INotifyPropertyChanged propChanged = _receiver as INotifyPropertyChanged;
                propChanged.PropertyChanged += new PropertyChangedEventHandler(propChanged_PropertyChanged);
            }
        }
 
        void propChanged_PropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            CanExecuteChanged(this, e);
        }
 
        public bool CanExecute(object parameter)
        {
            return parameter != null;
        }
 
        public event EventHandler CanExecuteChanged;
 
        public void Execute(object parameter)
        {
            if(parameter != null)
                MessageBox.Show(parameter.ToString());
        }
    }
}

About the Author

Eric Vogel is a Sr. Software Developer at Kunz, Leigh, & Associates in Okemos, MI. He is the president of the Greater Lansing User Group for .NET. Eric enjoys learning about software architecture and craftsmanship, and is always looking for ways to create more robust and testable applications. Contact him at vogelvision@gmail.com.