0

I am trying to use custom delegate command

But, an automatic RaiseCanExecuteChanged does not work properly. Is it nice to use CommandManagerHelper (every time when application in focus, it raise canexecute changed for every command? Or I have to use standart RelayCommand and raise canexecutechanged by myself ?

Thanks

Alex
  • 842
  • 11
  • 33

2 Answers2

1

The RaiseCanExecuteChanged event does not work properly in automated mode. Thus there is such implementation for every UI interaction to refresh canExecute handlers for RequerySuggested event. Code as follows (keep in mind, this implementation of ICommand is not performance effective, but works like a charm):

public class Command<TArgs> : ICommand
{
    public Command(Action<TArgs> exDelegate)
    {
        _exDelegate = exDelegate;
    }

    public Command(Action<TArgs> exDelegate, Func<TArgs, bool> canDelegate)
    {
        _exDelegate = exDelegate;
        _canDelegate = canDelegate;
    }

    protected Action<TArgs> _exDelegate;
    protected Func<TArgs, bool> _canDelegate;

    #region ICommand Members

    public bool CanExecute(TArgs parameter)
    {
        if (_canDelegate == null)
            return true;

        return _canDelegate(parameter);
    }

    public void Execute(TArgs parameter)
    {
        if (_exDelegate != null)
        {
            _exDelegate(parameter);
        }
    }

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

    bool ICommand.CanExecute(object parameter)
    {
        if (parameter != null)
        {
            var parameterType = parameter.GetType();
            if (parameterType.FullName.Equals("MS.Internal.NamedObject"))
                return false;
        }

        return CanExecute((TArgs)parameter);
    }

    void ICommand.Execute(object parameter)
    {
        Execute((TArgs)parameter);
    }

    #endregion
}
VidasV
  • 4,335
  • 1
  • 28
  • 50
  • Thanks, works fine. Where can I find information about main principle of how these commands work ? Espesially, about MS.Internal.NamedObject – Alex Jun 14 '13 at 11:14
  • I would suggest looking in MSDN libraries. I do not have direct link though. This implementation is quite an old one, back in a day when WPF just reached the day light :) – VidasV Jun 14 '13 at 11:36
0

The best solution is to use RelayCommand and raise CanExecuteChanged manually. Another solution do not work properly.

Alex
  • 842
  • 11
  • 33