I have a basic MVVM WPF app with a View, consisting of a texbox and submit button. Both controls are correctly binded to property and a command within ViewModel. The issue is that the CanSubmit is not triggered because CanExecuteChanged eventhandler (in DelegateCommand) is always null. Basically the question is how to properly notify Command to run CanExecute check when textox is updated.
public DelegateCommand SubmitCommand => new DelegateCommand(Submit, CanSubmit);
private string _company;
public string Company
{
get => _company;
set
{
SetProperty(ref _company, value);
SubmitCommand.RaiseCanExecuteChanged();
}
}
My delegate command
public class DelegateCommand : ICommand
{
private readonly Predicate<object> _canExecute;
private readonly Action<object> _execute;
public event EventHandler CanExecuteChanged;
public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
public DelegateCommand(Action<object> execute) : this(execute, null) { }
public virtual bool CanExecute(object parameter)
{
if (_canExecute == null)
{
return true;
}
return _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
public void RaiseCanExecuteChanged()
{
if(CanExecuteChanged != null) <------ Always null
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}