自从我开始使用 MVVM 以来,我一直使用 PRISM 的 DelegateCommand 类将我的 View 模型中的命令绑定(bind)到我的 View 中的按钮命令。我相信 Telerik 也有一个等效的 DelegateCommand。
我的问题是,是否有使用 prism 和 telerik 等 3rd 方框架的内置替代方案。如果我将一个快速的一次性应用程序放在一起,我可能不希望从 NuGet 安装包的麻烦。有没有办法使用 Func 或 Action 或委托(delegate)来实现相同的目标?
最佳答案
不,您仍然需要 Command
实现 ICommand
的类. 然而 ,你可以自己写DelegateCommand
真的很容易(引用,我在不到一分钟的时间内就写下了这个):
public class DelegateCommand : ICommand
{
private Action<object> execute;
public DelegateCommand(Action<object> executeMethod)
{
execute = executeMethod;
}
public bool CanExecute(object param)
{
return true;
}
public void Execute(object param)
{
if (execute != null)
execute(param);
}
}
使用和享受!你可以多拿一个
Func<bool, object>
参数如果你想要自定义 CanExecute
行为而不是返回 true。注意,如果你真的不喜欢
null
作为函数,并希望它在尝试时抛出,只需使用此构造函数即可: public DelegateCommand(Action<object> executeMethod)
{
if (executeMethod == null)
throw new ArgumentNullException("executeMethod");
execute = executeMethod;
}
关于c# - 没有 PRISM 的绑定(bind)命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28443573/