Raise context menu command's CanExcute while open the context menu

浪尽此生 提交于 2019-12-23 23:00:10

问题


Can Execute of a ICommand while a Context menu open

With the continuation of the above query, Still its not able to achieve.

Is there any way to raise context menu command's CanExcute while open the context menu. This need to be done in the context menu itself and here am not able to access the viewmodel.

Any idea on this?

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

            return saveCommand;
        }
    }

where BaseCommand is derived from 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:


Inside BaseCommand, replace the CanExecuteChanged to look like the following. And it will work the way you want it.

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


来源:https://stackoverflow.com/questions/18458509/raise-context-menu-commands-canexcute-while-open-the-context-menu

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!