5

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.

Andrey K.
  • 665
  • 8
  • 29

1 Answers1

9

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.

Shimmy Weitzhandler
  • 101,809
  • 122
  • 424
  • 632
alhpe
  • 1,424
  • 18
  • 24
  • Is there any reason not to just use a lambda here? The only thing I can think is that there is some caching of the resolves expression. – Gusdor Feb 09 '16 at 14:29
  • @Gusdor, as alphe said, It's because the ObserveCanExecute loosely replaces the [CanExecute](https://msdn.microsoft.com/en-us/library/ff654646.aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1) Boolean method; therefore, it has to return a Boolean value. – Steve Brother Aug 25 '17 at 15:50