4

我正在将 MVVM 模式应用于项目。我有一个 UserControl,它有一个按钮,该按钮绑定到 ViewModel 公开的命令。由于按钮是可见的,它不断地调用按钮的 CanExecute 方法。有些东西告诉我,这会带来性能损失,但我不确定。这是预期的行为吗?还是有更好的方法将按钮绑定到命令?

谢谢你。

4

1 回答 1

1

对不起,我发现了发生了什么。这是 RelayCommand 的实现。

public class RelayCommand : ICommand
{
    #region Fields

    readonly Action<object> _execute;
    readonly Predicate<object> _canExecute;

    #endregion // Fields

    #region Constructors

    public RelayCommand(Action<object> execute)
        : this(execute, null)
    {
    }

    public RelayCommand(Action<object> execute, Predicate<object> canExecute)
    {
        if (execute == null)
            throw new ArgumentNullException("execute");

        _execute = execute;
        _canExecute = canExecute;
    }
    #endregion // Constructors

    #region ICommand Members

    [DebuggerStepThrough]
    public bool CanExecute(object parameter)
    {
        return _canExecute == null ? true : _canExecute(parameter);
    }

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

    public void Execute(object parameter)
    {
        _execute(parameter);
    }

    #endregion // ICommand Members
}

我错误地认为系统正在自动重新查询所有命令。它实际上做的是挂钩每个命令的 CanExecuteChanged 事件,而 RelayCommand 基本上将其 CanExecuteChanged 事件链接到 CommandManager 的 RequerySuggested 事件,因此每次系统“建议”重新查询时,它实际上是在重新查询我所有的 RelayCommands。

谢谢你。

于 2010-12-01T17:41:37.933 回答