2

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);
    }

}
Community
  • 1
  • 1
Sankarann
  • 2,625
  • 4
  • 22
  • 59
  • 1
    Can you provide your `ICommand` implementation for the menu? It should normally work if you are delegating to `CommandManager` to raise the `CanExecute`. – Mat J Aug 27 '13 at 06:43
  • @Mathew: I have updated the code above, Is there any way to raise the canExcute. This context menu doest know what items its gonna carry but if the items of this context menu has any commands, it need to raise the can excute of ICommand. – Sankarann Aug 27 '13 at 07:03
  • Please show the implementation of `ICommand` ie, the class which implements that interface which, from your code, seems to be `BaseCommand`. Show the code which currently raising the `CanExecuteChanged` event inside `BaseCommand`. – Mat J Aug 27 '13 at 07:24

1 Answers1

0

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;
        }
    }
Mat J
  • 5,422
  • 6
  • 40
  • 56