Thanks in advance!
How should I use ObservesCanExecute in the DelegateCommand of PRISM 6?
public partial class UserAccountsViewModel: INotifyPropertyChanged
{
public DelegateCommand InsertCommand { get; private set; }
public DelegateCommand UpdateCommand { get; private set; }
public DelegateCommand DeleteCommand { get; private set; }
public UserAccount SelectedUserAccount
{
get;
set
{
//notify property changed stuff
}
}
public UserAccountsViewModel()
{
InitCommands();
}
private void InitCommands()
{
InsertCommand = new DelegateCommand(Insert, CanInsert);
UpdateCommand = new DelegateCommand(Update,CanUpdate).ObservesCanExecute(); // ???
DeleteCommand = new DelegateCommand(Delete,CanDelete);
}
//----------------------------------------------------------
private void Update()
{
//...
}
private bool CanUpdate()
{
return SelectedUserAccount != null;
}
//.....
}
Unfortunatelly, I'm not familiar with expressions in c#. Also, I thought this would be helpful to others.
ObservesCanExecute()
works “mostly like” the canExecuteMethod
parameter of DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod)
.
However, if you have a boolean property instead of a method, you don't need to define a canExecuteMethod
with ObservesCanExecute
.
In your example, suppose that CanUpdate
is not a method, just suppose that it's a boolean property.
Then you can change the code to ObservesCanExecute(() => CanUpdate)
and the DelegateCommand
will execute only if the CanUpdate
boolean property evaluates to true
(no need to define a method).
ObservesCanExecute
is like a “shortcut” over a property instead of having to define a method and having passing it to the canExecuteMethod
parameter of the DelegateCommand
constructor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With