Question

I'm currently toying a little with MVVM pattern and trying commands. I find the default way (every Command class needs to implement from ICommand interface) quite boring, so I've created a new base class called, wait for it, CommandBase. It looks like this:

public abstract class CommandBase : ICommand
{
    public virtual bool CanExecute(object parameter)
    {
        return true;
    }

    public virtual event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public virtual void Execute(object parameter)
    {

    }
}

Now every command just inherits from this base class and overrides what is necessary. I had a bug in the software, so I've put several breakpoints in my inheriting class and in this base class. Everything seems to work as expected, except one thing - the method CanExecute gets fired all the time. If I put the breakpoint inside the method, my application won't even start! If I delete this breakpoint, everything works again.

MainViewModel:

public class MainViewModel : ViewModelBase // base implements INotifyPropertyChanged
{
    public ICommand NavigateCommand { get; private set; }

    public MainViewModel()
    {
        NavigateCommand = new NavigateCommand(this);
    }
}

My debugger gets to the constructor, instantiate the Command class and from now on the method CanExecute fires like crazy and I can't even open the application window, because the vs debugger won't let me. In my NavigateCommand I only override Execute method and set one property of the MainViewModel, nothing too fancy. CanExecute is left intact without overriding.

Just a note, the bug I've mentioned was just a typo of my View, it wasn't related to this issue. After I've fixed it, code works except this thingy.

Can someone provide an explanation why it behaves like this?

Was it helpful?

Solution

It's a 'normal' behavior, that CanExecute gets fired often by the CommandManager. You shouldn't try to debug into this methods. In case of unknow bugs, turn on the Common Language Runtime Exceptions at Debug -> Exceptions... Further information here.

OTHER TIPS

Can I suggest that, unless absolutely necessary, you don't need to reinvent the wheel here. There are a number of excellent implementations of ICommand out there that you can use.

RelayCommand is probably the most commonly used, although DelegateCommand is also very well implemented, and is the standard ICommand implementation is the Prism framework.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top