How to require "CanExecute" of one RoutedCommand?

I need to update the state of CanExecuteone or more objects (although by no means all) RoutedCommand.

I know that you can update all commands using

CommandManager.InvalidateRequerySuggested();

Since this updates a lot more commands than necessary, calling this function is sometimes a performance issue in my application.

My initial hope was that a CanExecute()manual call would also raise an event if the state changes, but that is not the case.

When looking at the source CanExecuteChanged, it does not seem to be available for derived classes to provide some extension for the class RoutedCommand, which allows you to raise the event manually.

public event EventHandler CanExecuteChanged
{
    add { CommandManager.RequerySuggested += value; }
    remove { CommandManager.RequerySuggested -= value; }
}

, ? DelegateCommand, , , .

+4
1

RoutedCommand, reimplement ICommand . , new , WPF ICommand CanExecuteChanged.

public class MyRoutedCommand : RoutedCommand, ICommand
{
    private event EventHandler _canExecuteChanged;

    public void RaiseCanExecuteChanged()
    {
        var handler = _canExecuteChanged;
        if (handler != null) handler(this, EventArgs.Empty);
    }

    public new event EventHandler CanExecuteChanged
    {
        add
        {
            _canExecuteChanged += value;
            base.CanExecuteChanged += value;
        }
        remove
        {
            _canExecuteChanged -= value;
            base.CanExecuteChanged -= value;
        }
    }
}

, , WPF WeakEventManager , . , . , .

+3

Source: https://habr.com/ru/post/1537833/


All Articles