c# - 没有 PRISM 的绑定(bind)命令

标签 c# mvvm binding prism delegatecommand

自从我开始使用 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/

相关文章:

c# - XAML 布局问题

c# - 在 ConfigureServices (aspnetcore) 中获取 wwwroot 路径

ios - 带有 ReactiveCocoa 的 MVVM : limit the text length of a UITextField in view model

c# - 在 MVVM 中实现 ICommand 时,我遗漏了一些东西

c# - 如何简化具有许多属性的viewmodel/model的使用?

c# - C# 和 VB 如何处理命名参数之间的差异?

wpf - 绑定(bind)多个 View 模型

android - 如何使用 MvvmCross 将 Android TextView 绑定(bind)到 Click 事件

c# - wcf + 响应消息的内容类型text/html与绑定(bind)的内容类型不匹配(application/soap+xml; charset=utf-8)

c# - SOAP - namespace ,这是做什么用的?