WPF PRISM 6 DelegateComand ObservesCanExecute
Asked Answered
U

1

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.

Umpteen answered 14/12, 2015 at 12:20 Comment(0)
G
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.

Galleon answered 16/12, 2015 at 16:20 Comment(2)
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.Crosley
@Gusdor, as alphe said, It's because the ObserveCanExecute loosely replaces the CanExecute Boolean method; therefore, it has to return a Boolean value.Coffer

© 2022 - 2024 — McMap. All rights reserved.