之前提及到在WPF 中利用Mode-View-ViewModel (MVVM) 中作EventHandling, 而一般的command binding 則須要自建class 去處理.DelegateCommand.cs
public class DelegateCommand : ICommand
{
private readonly Predicate<object> _canExecute;
private readonly Action<object> _execute;
public event EventHandler CanExecuteChanged;
public DelegateCommand(Action<object> execute)
: this(execute, null)
{
}
public DelegateCommand(Action<object> execute,
Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
public bool CanExecute(object parameter)
{
if (_canExecute == null)
{
return true;
}
return _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
public void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
利用 DelegateCommand Implement ICommand, 並於constructor 中加入Execute() 及CanExecute().
而叫用時, 在ViewModel 中則使用方法如下:
public DelegateCommand SaveCommand;
protected void SaveCommandExecute(object parameter)
{
// Command action.
}
protected bool SaveCommandCanExecute(object parameter)
{
// Command can execute or not.
return true;
}
public MainWindowViewModel() : base()
{
// Define command and set property change handling.
SaveCommand = new DelegateCommand(SaveCommandExecute, SaveCommandCanExecute);
this.PropertyChanged += MainWindowViewModel_PropertyChanged;
}
private void MainWindowViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
// Fire event to execute CanExecute().
SaveCommand.RaiseCanExecuteChanged();
}
Leave a Reply