我正在将MVVM模式应用于项目.我有一个UserControl,它有一个按钮,该按钮绑定到ViewModel公开的命令. 由于按钮是可见的,因此它会持续调用按钮的CanExecute方法.有些东西告诉我,这会带来性能损
由于按钮是可见的,因此它会持续调用按钮的CanExecute方法.有些东西告诉我,这会带来性能损失,但我不确定.这是预期的行为吗?或者是否有更好的方法让按钮绑定到命令?
谢谢.
对不起,我发现了发生了什么事.这是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
}
我错误地认为系统是自动重新查询所有命令.它实际上做的是挂钩每个Command的CanExecuteChanged事件,并且RelayCommand基本上将其CanExecuteChanged事件链接到CommandManager的RequerySuggested事件,因此每次系统“建议”一个requery时,它实际上是在重新查询我的所有RelayCommands.
谢谢.
