I have a DelegateCommand
that looks like so:
public class DelegateCommand : ICommand
{
private readonly Predicate<object> _canExecute;
private readonly Action<object> _execute;
public event EventHandler CanExecuteChanged;
public DelegateCommand(Action<object> execute)
: this(execute, null)
{
}
public DelegateCommand(Action<object> execute, Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
return _canExecute == null || _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
public void RaiseCanExecuteChanged()
{
CanExecuteChanged?.Invoke(this, EventArgs.Empty);
}
}
I have a process that allows the user to register onto a database. However, I need to add some validation in for example, does the username already exist, does the password match rules etc. Here is the register command:
#region RegisterCommand
private DelegateCommand _registerCommand;
public ICommand RegisterCommand
{
get
{
_registerCommand = new DelegateCommand(param => Register());
return _registerCommand;
}
}
private bool CanRegister()
{
return true;
}
private void Register()
{
var newUser = new User
{
FirstName = _firstname,
LastName = _lastname,
Username = _username,
Password = "", // TODO: Hashing and storing of passwords
};
using (var context = new WorkstreamContext())
{
var users = context.Set<User>();
users.Add(newUser);
context.SaveChanges();
}
}
#endregion
As you can see, I have a method called CanRegister()
that I want to use to filter through the registration process. My question is, how would I implement CanRegister()
in the call here:
_registerCommand = new DelegateCommand(param => Register());
that prompts or denies the process if CanRegister
returns false?