In my ViewModel I have implemented IDataErrorInfo
interface (along with INotifyPropertyChanged
). Input validation works as intended, I have no problems there.
I have this property as part of IDataErrorInfo
public string Error { get { return this[null]; } }
To my understanding, Error
should be empty if all validated inputs pass validation, so I pass this as my CanExecute method
return !string.IsNullOrEmpty(Error);
But, my "save" button never gets enabled. My guess is that CanExecuteChanged
never gets triggered. If that's true, where and how should I trigger it?
This is my RelayCommand
class. I have tried other ways of implementation, but the results were the same. I think it works, because the "save" button is enabled if I don't pass CanExecute
method to the constructor.
public class RelayCommand : ICommand
{
private readonly Action execute;
private readonly Func<bool> canExecute;
public RelayCommand(Action execute, Func<bool> canExecute = null)
{
this.execute = execute;
this.canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return canExecute == null || canExecute();
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
public void Execute(object parameter) { execute(); }
}
The "save" button:
<Button Content="Save" Command="{Binding InsertCommand}"/>
InsertCommand:
public RelayCommand InsertCommand { get; internal set; }
In the ViewModel constructor:
InsertCommand = new RelayCommand(ExecuteInsert, CanExecuteInsert);
CanExecute:
bool CanExecuteInsert()
{
return !string.IsNullOrEmpty(Error);
}