MVVM Light CanExecute Command - Re-evaluate en-mass

March 07, 2015

MVVM Light CanExecute doesn’t work for commands

The following code in MVVM light does not work:



RelayCommand newCommand = new RelayCommand(onExecute, canExecute);

. . . 

canExecute = true;

. . .

canExecute = false;

That is, the bound command will not update. Even if the changed `canExecute` raises property changed.

Raise it manually

So, the way to fix this is as follows:



        public bool canExecute
        {
            get { return \_canExecute; }
            set
            {
                \_canExecute = value;
                RaisePropertyChanged();
                newCommand.RaiseCanExecuteChanged();
            }
        }

Which works fine. However, what if you have 10 commands, and they all have the same dependant property?

Real life

Here’s my method of working around this. Is it effectively a `RaiseAllPropertyChanged()` for commands. Start with a class level list of commands:



        // Store a local list of all registered commands to inform of updates
        private List<RelayCommand> \_registeredCommands;

Now create a function that allows us to iterate this and call RaiseCanExecuteChanged to all of them:



        private void ReevaluateCommands()
        {
            foreach (var eachCommand in \_registeredCommands)
            {
                eachCommand.RaiseCanExecuteChanged();
            }

        }

Finally, we can simply call this when the dependant property changes:



        public bool canExecute
        {
            get { return \_canExecute; }
            set
            {
                \_canExecute = value;
                RaisePropertyChanged();
                ReevaluateCommands();
            }
        }

Magic.

Disclaimer

I kind of stole the idea for this from here. I’m not selling this as a massively scalable, all singing, all dancing solution. It just works for my particular scenario, which is here:

TFS Utilities



Profile picture

A blog about one man's journey through code… and some pictures of the Peak District
Twitter

© Paul Michaels 2024