Il modo corretto per gestire i pulsanti è implementare l'interfaccia ICommand. Ecco un esempio dalla mia soluzione:
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
}
È possibile quindi databind a pulsante mi piace questo:
<Button Command="{Binding MyCommand}" .../>
ciò che resta è dichiarare una proprietà ICommand
sul tuo ViewModel:
public ICommand MyCommand { get; private set; }
//in constructor:
MyCommand = new RelayCommand(_ => SomeActionOnButtonClick(), _ => HasChanges);
Lo stato del pulsante si aggiornerà automaticamente sulla maggior parte delle modifiche. Se per qualche motivo non funziona, puoi forzare l'aggiornamento chiamando lo CommandManager.InvalidateRequerySuggested
fonte
2013-08-19 10:43:30