我创建了一个实现ICommand的基本视图模型。这些命令绑定得很好,可以按预期执行,甚至可以在正确的状态下开始,但是由于会影响命令能否执行或更改的属性,这些命令的CanExecute似乎没有更新。
在下面的代码中,我可以单击“运行”按钮,并且除了ProgramStatus更改为“正在运行”时应禁用该事实之外,其他所有功能均按预期运行。
在我的基本视图模型中:
public class RelayCommand : ICommand
{
#region ICommand Member Variables
private Action<object> _execute;
private Predicate<object> _canExecute;
private event EventHandler _canExecuteChangedInternal;
#endregion // ICommand Member Variables
#region Constructors
public RelayCommand(Action<object> execute, Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
public RelayCommand(Action<object> execute) : this(execute, DefaultCanExecute)
{
}
#endregion // Constructors
#region ICommand Members
public event EventHandler CanExecuteChanged
{
add
{
CommandManager.RequerySuggested += value;
_canExecuteChangedInternal += value;
}
remove
{
CommandManager.RequerySuggested -= value;
_canExecuteChangedInternal -= value;
}
}
public bool CanExecute(object parameter)
{
return _canExecute != null && _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
public void OnCanExecuteChanged()
{
EventHandler eventHandler = _canExecuteChangedInternal;
if (eventHandler != null)
{
eventHandler.Invoke(this, EventArgs.Empty);
}
}
private static bool DefaultCanExecute(object parameter)
{
return true;
}
#endregion // ICommand Members
在我的视图模型中:
RelayCommand _runCommand;
public RelayCommand RunCommand
{
get
{
if (_runCommand == null)
{
_runCommand = new RelayCommand(param => Run(), param => CanRun);
}
return _runCommand;
}
}
public bool CanRun
{
get
{
bool result = false;
if (Machine.ProgramStatus != ProgramStatus.Running && Machine.ProgramStatus != ProgramStatus.TestRunning)
{
result = true;
}
return result;
}
}
我认为:
<Button Content="Run" Command="{Binding Path=RunCommand}" />
答案 0 :(得分:1)
您必须调用CanExecuteChanged EventHandler。因此,当ProgramStatus更改为Running时,可以为要更新的命令(例如OnCanExecuteChanged
)调用RunCommand.OnCanExecuteChanged();
帮助方法。
如果CanExecute绑定到属性,则可以使用属性设置器中的OnCanExecuteChanged帮助器方法。
private bool _myProperty;
public bool MyProperty
{
get { return _myProperty; }
set
{
_myProperty= value;
RunCommand.OnCanExecuteChanged();
}
}