WPF SimpleCommand possible with generics?

北城余情 提交于 2019-12-03 20:30:51
Kent Boogaart

Sure. Was gonna point you to Prism's implementation, but CodePlex source tab seems to not be working. It would look something like:

public class SimpleCommand<T> : ICommand
{
    public Predicate<T> CanExecuteDelegate { get; set; }
    public Action<T> ExecuteDelegate { get; set; }

    #region ICommand Members

    public bool CanExecute(object parameter)
    {
        if (CanExecuteDelegate != null)
            return CanExecuteDelegate((T)parameter);
        return true;// if there is no can execute default to true
    }

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

    public void Execute(object parameter)
    {
        if (ExecuteDelegate != null)
            ExecuteDelegate((T)parameter);
    }

    #endregion
}

Incidentally, your usage of SimpleCommand in your question is a little roundabout. Instead of this:

DoSomethingCommand = new SimpleCommand
                    {
                        ExecuteDelegate = x => RunCommand(x)
                    };

You could just have:

DoSomethingCommand = new SimpleCommand
                    {
                        ExecuteDelegate = this.RunCommand
                    };

Specifying a lambda is really only useful if you're doing the work inline like this:

DoSomethingCommand = new SimpleCommand
                    {
                        ExecuteDelegate = o => this.SelectedItem = o,
                        CanExecuteDelegate = o => o != null
                    };
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!