处理按钮的正确方法是实现ICommand接口。这是我的解决方案中的一个示例:
public class RelayCommand : ICommand
{
readonly Action<object> _execute;
readonly Predicate<object> _canExecute;
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;
}
#region ICommand Members
public bool CanExecute(object parameter)
{
return _canExecute == null ? true : _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
#endregion
}
然后,您可以像这样将数据绑定到按钮:
<Button Command="{Binding MyCommand}" .../>
剩下的就是ICommand
在你的视图模型上声明一个属性:
public ICommand MyCommand { get; private set; }
//in constructor:
MyCommand = new RelayCommand(_ => SomeActionOnButtonClick(), _ => HasChanges);
然后按钮的状态将根据大多数更改自动更新。如果由于某种原因没有 - 您可以通过调用强制更新CommandManager.InvalidateRequerySuggested