我有一个带有按钮的简单程序,该按钮绑定到View模型中的Relaycommand,如下所示。我根据某个值设置CanExecute为true(由计时器设置,您可以在下面找到详细信息)。我的按钮已启用当Status为3时,最初是我在构造函数中设置的。但是当Status值自行更改时它不会被禁用。我只能在点击它时看到禁用。任何人都可以解释为什么它不会禁用它自己的
public class MainWindowViewModel : INotifyPropertyChanged
{
private RelayCommand mClickButtonCommand;
private int mStatus;
private Timer mTimer;
public MainWindowViewModel()
{
Status = 3;
mTimer = new Timer(1000);
mTimer.Elapsed += OnElapsed;
mTimer.Start();
}
private void OnElapsed(object sender, ElapsedEventArgs e)
{
if (Status == 5)
{
Status = 0;
}
Status++;
}
public ICommand ClickButtonCommand
{
get
{
if (mClickButtonCommand == null)
{
mClickButtonCommand = new RelayCommand(OnClick, () => CanClick);
}
return mClickButtonCommand;
}
}
private void OnClick()
{
Console.WriteLine("Clicked");
}
public bool CanClick
{
get { return Status == 3; }
}
public int Status
{
get { return mStatus; }
set
{
mStatus = value;
OnPropertyChanged("Status");
OnPropertyChanged("CanClick");
}
}
public event PropertyChangedEventHandler PropertyChanged;
[NotifyPropertyChangedInvocator]
protected virtual void OnPropertyChanged(string propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
}
}
我的realy命令实现是
public class RelayCommand : ICommand
{
public RelayCommand(Action execute)
: this(execute, null)
{
}
public RelayCommand(Action execute, Func<bool> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
_execute = execute;
_canExecute = canExecute;
}
#region ICommand Members
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute();
}
public event EventHandler CanExecuteChanged
{
add
{
if (_canExecute != null)
CommandManager.RequerySuggested += value;
}
remove
{
if (_canExecute != null)
CommandManager.RequerySuggested -= value;
}
}
public void Execute(object parameter)
{
_execute();
}
#endregion // ICommand Members
#region Fields
readonly Action _execute;
readonly Func<bool> _canExecute;
#endregion // Fields
}
答案 0 :(得分:1)
感谢您的输入,我通过在relaycommand实现中添加CommandManager.InvalidateRequerySuggested解决了我的问题。
[DebuggerStepThrough]
public bool CanExecute(object parameter)
{
bool result = true;
if (_canExecute != null)
{
result = _canExecute();
CommandManager.InvalidateRequerySuggested();
}
return result;
}
答案 1 :(得分:0)
与引发PropertyChanged事件的方式相同,您可以引发CanExecuteChanged事件......
ClickButtonCommand.RaiseCanExecuteChanged();