Click here to Skip to main content
15,893,594 members
Articles / Desktop Programming / WPF

Using RoutedCommands with a ViewModel in WPF

Rate me:
Please Sign up or sign in to vote.
4.96/5 (56 votes)
24 Jul 2008CPOL8 min read 589.2K   4.1K   153  
Reviews a clean and lightweight way to use RoutedCommands in the MVVM pattern.
using System;
using System.ComponentModel;
using System.Windows;
using System.Windows.Input;
using VMCommanding.Model;

namespace VMCommanding.ViewModel
{
    /// <summary>
    /// A ViewModel class that wraps a Person object
    /// and provides some UI-specific behavior via
    /// routed commands, such as speaking and dying.
    /// This class uses a CommandSink object, because 
    /// it does not derive from that class.  See
    /// the CommunityViewModel for an example of deriving
    /// from CommandSink.
    /// </summary>
    public class PersonViewModel :
        ICommandSink,
        INotifyPropertyChanged
    {
        #region Data

        readonly CommandSink _commandSink;
        readonly Person _person;        

        #endregion // Data

        #region Constructor

        public PersonViewModel(Person person)
        {
            _person = person;

            _commandSink = new CommandSink();

            _commandSink.RegisterCommand(
                DieCommand, 
                param => this.CanDie,
                param => this.Die());

            _commandSink.RegisterCommand(
                SpeakCommand,
                param => this.CanSpeak,
                param => this.Speak(param as string));
        }

        #endregion // Constructor

        #region Person Properties

        public int Age
        {
            get { return _person.Age; }
        }

        public string Name
        {
            get { return _person.Name; }
        }

        #endregion // Person Properties

        #region Die

        public static readonly RoutedCommand DieCommand = new RoutedCommand();

        public bool CanDie
        {
            get { return _person.IsAlive; }
        }

        public void Die()
        {
            _person.IsAlive = false;

            this.OnPropertyChanged("CanDie");
            this.OnPropertyChanged("CanSpeak");
        }

        #endregion // Die

        #region Speak

        public static readonly RoutedCommand SpeakCommand = new RoutedCommand();

        public bool CanSpeak
        {
            get { return _person.IsAlive; }
        }

        public void Speak(string whatToSay)
        {
            string msg = whatToSay ?? String.Empty;
            string title = _person.Name + " says...";
            MessageBox.Show(whatToSay, title);
        }

        #endregion // Speak        

        #region ICommandSink Members

        public bool CanExecuteCommand(ICommand command, object parameter, out bool handled)
        {
            return _commandSink.CanExecuteCommand(command, parameter, out handled);
        }

        public void ExecuteCommand(ICommand command, object parameter, out bool handled)
        {
            _commandSink.ExecuteCommand(command, parameter, out handled);
        }

        #endregion // ICommandSink Members

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        void OnPropertyChanged(string propertyName)
        {
            if (this.PropertyChanged != null)
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion // INotifyPropertyChanged Members
    }
}

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)
United States United States
Josh creates software, for iOS and Windows.

He works at Black Pixel as a Senior Developer.

Read his iOS Programming for .NET Developers[^] book to learn how to write iPhone and iPad apps by leveraging your existing .NET skills.

Use his Master WPF[^] app on your iPhone to sharpen your WPF skills on the go.

Check out his Advanced MVVM[^] book.

Visit his WPF blog[^] or stop by his iOS blog[^].

See his website Josh Smith Digital[^].

Comments and Discussions