Over a million developers have joined DZone.

AutoCommand For MVVM – More tricks With Lambdas and CallerMemberName

DZone 's Guide to

AutoCommand For MVVM – More tricks With Lambdas and CallerMemberName

· Web Dev Zone ·
Free Resource

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

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}