When I use a DelegateCommand
, I just manually raise the CanExecuteChanged
in the PropertyChange
event whenever a property the command relies on changes.
Here's an example I did a few days ago where the CanExecute
was based off the IsLoading
and IsValid
properties:
public MyViewModel()
{
this.PropertyChanged += MyViewModel_PropertyChanged;
}
void MyViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
switch (e.PropertyName)
{
case "IsLoading":
case "IsValid":
((DelegateCommand)MyCommand).RaiseCanExecuteChanged();
break;
}
}
public ICommand MyCommand
{
get
{
if (_myCommand == null)
_myCommand = new DelegateCommand(Run, CanRun);
return _myCommand;
}
}
public bool CanRun()
{
return this.IsValid && !IsLoading;
}
I find this keeps the logic easy to follow and maintain, and it only checks the CanExecuteChanged()
method when the relevant properties change.