I am coding a simple login UserControl with two TextBoxes (Username and Password) and a Login button. I want the Login button to be enabled only when the username and password f
Starting with Prism6 the DelegateCommand
can "observe" your propertys. Means everytime your property is changing the CanExecute-Method is called. The good thing is you get rid of RaiseCanExecuteChanged
in the Propertysetter. You can also chain-call that method if you want to observe more properties:
public LoginViewModel()
{
this.LoginCommand =
new DelegateCommand<object>(
this.LoginExecute, this.CanLoginExecute).ObservesProperty(() => Username).ObservesProperty(() => Password);
}
Furthermore if you just want your DelegateCommand be called depending on the state of a boolean property you can use .ObservesCanExecute(()=> BoolProp)
public LoginViewModel()
{
this.LoginCommand =
new DelegateCommand<object>(
this.LoginExecute).ObservesCanExecute(()=> IsServerOnline).ObservesProperty(() => Username).ObservesProperty(() => Password);
}
You dont need this.CanLoginExecute
anymore.
Code for RaiseCanExecuteChanged:
private void RaiseCanExecuteChanged()
{
DelegateCommand<object> command = LoginCommand as DelegateCommand<object>;
command.RaiseCanExecuteChanged();
}
public const string UsernameProperty = "Username";
private String _username;
public String Username
{
get { return _username; }
set
{
_username = value;
this.NotifyPropertyChanged(UsernameProperty);
RaiseCanExecuteChanged();
}
}
It is most likely that the bound control is never asking for the CanExecute state again. You need to call the RaiseCanExecuteChanged method on the DelegateCommand whenever you detect a condition that changes the command's CanExecute state. This signals the bound control to update the CanExecute state.
Here's a little workaround for Prism (tested with Prism.Core 7.1.0.431):
public class RelayCommand : DelegateCommand
{
public RelayCommand(Action executeMethode) : base(executeMethode)
{
}
public RelayCommand(Action executeMethode, Func<bool> canExecuteMethode) : base(executeMethode, canExecuteMethode)
{
}
public override event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
}