Question

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

Was it helpful?

Solution

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
}

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top