Jer*_*xon 15 windows-8 winrt-xaml
将命令抽象到View Model中是XAML/MVVM项目的一个有价值的实践.我明白了.而且,我在WinRT中看到了ICommand; 但是,我们如何实现它?我还没有找到实际可行的样本.谁知道?
Sha*_*rot 20
我最喜欢的是Microsoft模式和实践团队提供的DelegateCommand.它允许您创建一个类型化的命令:
MyCommand = new DelegateCommand<MyEntity>(OnExecute);
...
private void OnExecute(MyEntity entity)
{...}
Run Code Online (Sandbox Code Playgroud)
它还提供了一种引发CanExecuteChanged事件的方法(禁用/启用命令)
MyCommand.RaiseCanExecuteChanged();
Run Code Online (Sandbox Code Playgroud)
这是代码:
public class DelegateCommand<T> : ICommand
{
private readonly Func<T, bool> _canExecuteMethod;
private readonly Action<T> _executeMethod;
#region Constructors
public DelegateCommand(Action<T> executeMethod)
: this(executeMethod, null)
{
}
public DelegateCommand(Action<T> executeMethod, Func<T, bool> canExecuteMethod)
{
_executeMethod = executeMethod;
_canExecuteMethod = canExecuteMethod;
}
#endregion Constructors
#region ICommand Members
public event EventHandler CanExecuteChanged;
bool ICommand.CanExecute(object parameter)
{
try
{
return CanExecute((T)parameter);
}
catch { return false; }
}
void ICommand.Execute(object parameter)
{
Execute((T)parameter);
}
#endregion ICommand Members
#region Public Methods
public bool CanExecute(T parameter)
{
return ((_canExecuteMethod == null) || _canExecuteMethod(parameter));
}
public void Execute(T parameter)
{
if (_executeMethod != null)
{
_executeMethod(parameter);
}
}
public void RaiseCanExecuteChanged()
{
OnCanExecuteChanged(EventArgs.Empty);
}
#endregion Public Methods
#region Protected Methods
protected virtual void OnCanExecuteChanged(EventArgs e)
{
var handler = CanExecuteChanged;
if (handler != null)
{
handler(this, e);
}
}
#endregion Protected Methods
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6945 次 |
| 最近记录: |