博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
在MVVM模式中,按钮Click事件的绑定方法
阅读量:7110 次
发布时间:2019-06-28

本文共 1146 字,大约阅读时间需要 3 分钟。

原文:

  在MVVM模式中,我们将Button的方法写到ViewModel中,然后绑定到前端界面。通常的做法是写一个类,继承ICommand接口,然而如果按钮比较多的话,就需要写很多的类,对于后期维护造成很大的不变,微软提供了一个DelegateCommand类,可以简化开发。

使用方法如下:

首先生命ViewModel属性,GetMsg函数,

public DelegateCommand GetMsg       {         get { return new DelegateCommand(GetMessage); }      }

在ViewModel中写方法GetMessage,代码如下:

public void GetMessage(object parameter)      {
//Your code... }

然后在前端绑定,代码如下:

 

其实,DelegateCommand只是一个继承自ICommand的类,下面我们来写自己的DelegateCommand类,实现同样的功能。代码如下:

public class DelegateCommand : ICommand   {      private Action action;      private Action actionT;      public DelegateCommand(Action action)      {         this.action = action;      }      public DelegateCommand(Action action)      {         this.actionT = action;      }      public bool CanExecute(object parameter)      {         return true;      }      public event EventHandler CanExecuteChanged;      public void Execute(object parameter)      {         if (action != null)         {            action();         }         if (actionT != null)         {            actionT.Invoke(parameter);         }      }   }

这个类有两个构造方法,有参数的和无参数的,可以根据自己的需要扩展,使用起来非常方便。

 

转载地址:http://unlhl.baihongyu.com/

你可能感兴趣的文章
http与https的区别
查看>>
【JavaScript】ReactJS&NodeJS了解资料
查看>>
springMVC demo搭建
查看>>
JAXB完毕XML与Java对象的互转
查看>>
Android 自定义ViewGroup
查看>>
特级教师总结的教育之33条(ZZ)
查看>>
AESwithJCE http://www.coderanch.com/how-to/content/AES_v1.html
查看>>
基于keepalived搭建MySQL的高可用集群
查看>>
CTeX学习心得总结
查看>>
运算放大器相关参数基本知识(一)
查看>>
Maven中解决依赖冲突的问题
查看>>
iOS Json转换模型库:YYModel
查看>>
u-boot 2011.09 开启debug 调试
查看>>
Redis主从配置详细过程
查看>>
Swift和Objective-C混编注意
查看>>
沈阳赛区总结
查看>>
自然语言1_介绍和安装
查看>>
git: windows git ssh keys生成
查看>>
转: 系统分布式情况下最终一致性方案梳理
查看>>
Webpack学习笔记一:What is webpack
查看>>