gpt4 book ai didi

windows-8 - 有没有 WinRT iCommand/CommandBinding 实现示例?

转载 作者:行者123 更新时间:2023-12-03 20:15:21 24 4
gpt4 key购买 nike

将命令抽象到 View 模型中对于 XAML/MVVM 项目来说是一种很有值(value)的做法。我明白了。而且,我在 WinRT 中看到了 ICommand;但是,我们如何实现呢?我还没有找到真正有效的样本。有人知道吗?

最佳答案

我一直最喜欢的是 Microsoft 模式和实践团队提供的 DelegateCommand。它允许您创建键入的命令:

MyCommand = new DelegateCommand<MyEntity>(OnExecute);
...
private void OnExecute(MyEntity entity)
{...}

它还提供了一种引发 CanExecuteChanged 事件的方法(禁用/启用命令)

MyCommand.RaiseCanExecuteChanged();

这是代码:

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
}

关于windows-8 - 有没有 WinRT iCommand/CommandBinding 实现示例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11960488/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com