處理按鈕的正確方法是實現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
}
然後,您可以數據綁定到按鈕這樣的:
public ICommand MyCommand { get; private set; }
//in constructor:
MyCommand = new RelayCommand(_ => SomeActionOnButtonClick(), _ => HasChanges);
:
<Button Command="{Binding MyCommand}" .../>
請告訴我剩下的就是你的視圖模型聲明ICommand
財產然後按鈕的狀態會自動更新大部分更改。如果它不是由於某種原因 - 您可以致電CommandManager.InvalidateRequerySuggested