HTML5 Zone is brought to you in partnership with:

Presently working as a Solution Architect building offerings, enabling delivery and providing solutions and strategies across multiple customers and domains. Speciality in Microsoft Technologies, Cloud technologies and WOA. Focused on DDD practices, with a sharp interest in highly scalable architectures like CQRS. Anoop is a DZone MVB and is not an employee of DZone and has posted 14 posts at DZone. You can read more from them at their website. View Full User Profile

AutoCommand For MVVM – More tricks With Lambdas and CallerMemberName

  • submit to reddit

imageA few days back I ranted about Lamdba Patterns in C# and Init Time branching.  I also had a generally insane example regarding Init Time branching using CallerMemberName attribute, and got few comments about the usefulness (or the lack of the same).

While I generally agree with the comments, here is a maybe useful, still crazy AutoCommand for your next basement MVVM application. First, here is how the AutoCommand will work.

//Our simple View Model
public class SimpleMathViewModel : BaseViewModel
        public SimpleMathViewModel()
            Commands = new Dictionary<string, Action>
                    {"Add", ()=>Result=A+B},
                    {"Substract", ()=>Result=A-B},
                    {"Multiply", ()=>Result=A*B},
                    {"Divide", ()=>Result=A/B}

        //Your commands should get automatically wired up

        public ICommand Add { get { return new AutoCommand(this); } }
        public ICommand Substract { get { return new AutoCommand(this); } }
        public ICommand Multiply { get { return new AutoCommand(this); } }
        public ICommand Divide { get { return new AutoCommand(this); } }

        //Other blah blah properties
        public int A { get; set; }
        public int B { get; set; }

        private int _result;
        public int Result
            get { return _result; }
                _result = value; OnPropertyChanged();

Also, Look ma, there is no dirty property name string in the OnPropertyChanged method call to raise the PropertyChanged notification as it is inferred  - but I'm sure you might have read some where else how to use CallerMemberName to do the trick. If you are still wondering, see the method implementation in the BaseViewModel code below.

Leaving that aside – how’z the wiring works for AutoCommand? Alright, guess you guessed it. Here is the AutoCommand implementation.

   public class AutoCommand : ICommand
        private readonly BaseViewModel _instance;
        private readonly string _caller;

        //Just keep the caller name and the base view model instance
        public AutoCommand(BaseViewModel instance, 
                [CallerMemberName]string caller = "")
            _instance = instance;
            _caller = caller;

        public bool CanExecute(object parameter)
            return true; //who cares

        //Fetch the right command to execute from the dictionary
        public void Execute(object parameter)
            _instance.Commands[_caller](); //get the ICommand based on the caller name

        public event EventHandler CanExecuteChanged;

And if you are wondering how we've implemented the BaseViewModel, it is trivial. There only interesting piece there is how we inject the property name to the base class method.

 public abstract class BaseViewModel : INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;
        public Dictionary<string, Action> Commands { get; set; }

        protected virtual void OnPropertyChanged([CallerMemberName]string propertyName="")
            PropertyChangedEventHandler handler = PropertyChanged;
            if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));

This is not a best practice show case, was just discussing a language feature and few possibilities. Happy and Insane coding Smile

Published at DZone with permission of Anoop Madhusudanan, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)