Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF PRISM 6 DelegateComand ObservesCanExecute

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.

like image 823
Andrey K. Avatar asked Dec 14 '15 12:12

Andrey K.


1 Answers

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.

like image 123
alhpe Avatar answered Nov 06 '22 06:11

alhpe