Click here to Skip to main content
15,886,808 members
Articles / Desktop Programming / WPF

MVVM Dynamic Commands

Rate me:
Please Sign up or sign in to vote.
4.56/5 (5 votes)
24 Apr 2009CPOL6 min read 61.1K   1.4K   34  
Implementing dynamic WPF ICommands in Model-View-ViewModel architecture
using System;
using System.Windows.Data;
using System.Windows.Input;

namespace ListBoxHyperlinkDemo.ViewModel
{
    [ValueConversion(typeof(string), typeof(ICommand))]
    public class CommandConverter : IValueConverter
    {
        #region fields

        // Member variables
        private MainWindowViewModel m_ViewModel;

        #endregion

        #region Constructor

        public CommandConverter(MainWindowViewModel viewModel)
        {
            m_ViewModel = viewModel;
        }

        #endregion

        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            // Exit if value is null
            if (value == null) return null;

            // Initialize
            string commandName = value.ToString();
            MainWindowViewModel viewModel = (MainWindowViewModel)parameter;
            ICommand command = null;

            // Create command 
            switch (commandName)
            {
                case "CompleteTransaction":
                    command = new CompleteTransaction(m_ViewModel);
                    break;

                case "ReviewAccount":
                    command = new ReviewAccout(m_ViewModel);
                    break;

                default:
                    throw new ArgumentException("Invalid ICommand name passed in.");
            }

            // Set return value
            return command;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #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
Software Developer (Senior) Foresight Systems
United States United States
David Veeneman is a financial planner and software developer. He is the author of "The Fortune in Your Future" (McGraw-Hill 1998). His company, Foresight Systems, develops planning and financial software.

Comments and Discussions