打开上下文菜单时,引发上下文菜单命令CanExecute

时间:2013-08-27 06:34:00

标签: wpf command contextmenu icommand

Can Execute of a ICommand while a Context menu open

随着上述查询的延续,仍然无法实现。

有没有办法在打开上下文菜单时引发上下文菜单命令的CanExcute。这需要在上下文菜单中完成,这里无法访问viewmodel。

对此有什么想法吗?

    public static BaseCommand SaveCommand
    {
        get
        {
            if (saveCommand == null)
                saveCommand = new BaseCommand(OnSaveCommandClicked, OnSaveCommandCanExcute);

            return saveCommand;
        }
    }

其中BaseCommand派生自ICommand。

public class BaseCommand : ICommand
{
    private Predicate<object> _canExecute;
    private Action<object> _method;
    public event EventHandler CanExecuteChanged;

    public BaseCommand(Action<object> method)
        : this(method, null)
    {
    }

    public BaseCommand(Action<object> method, Predicate<object> canExecute)
    {
        _method = method;
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        if (_canExecute == null)
        {
            return true;
        }

        return _canExecute(parameter);
    }

    public void Execute(object parameter)
    {
        _method.Invoke(parameter);
    }

}

1 个答案:

答案 0 :(得分:0)

BaseCommand内,将CanExecuteChanged替换为如下所示。它会以你想要的方式工作。

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