在WPF的MVVM模式中,View和ViewModel之间数据和命令的关联都是通过绑定实现的,绑定后View和ViewModel并不产生直接的依赖。具体就是View中出现数据变化时会尝试修改绑定的目标。同样View执行命令时也会去寻找绑定的Command并执行。反过来,ViewModel在Property发生改变时会发个通知说“名字叫XXX的Property改变了,你们这些View中谁绑定了XXX也要跟着变啊!”,至于有没有View收到是不是做出变化也不关心。ViewModel中的Command脱离View就更简单了,因为Command在执行操作过程中操作数据时,根本不需要操作View中的数据,只需要操作ViewModel中的Property就可以了,Property的变化通过绑定就可以反映到View上。这样在测试Command时也不需要View的参与。这也是我在接触WPF初期时根本理解不了的所谓数据驱动。

这样一来ViewMode可以在完全没有View的情况下测试,View也可以在完全没有ViewModel的情况下测试(当然只是测试界面布局和动画等业务无关的内容)。

1、App中的代码:

public App()

{

    CalculatorView view = new CalculatorView();

    view.DataContext = new CalculatorViewModel();

    view.Show();

}

2、Model层中CauculatorModel的代码

class CauculatorModel

{

     public string FirstOperand { getset; }

     public string SecondOperand { getset; }

     public string Operation { getset; }

     public string Result { getset; }

}

3、Command

public class DeletgateCommand<T>:ICommand

 {

     private readonly Action<T> _executeMethod = null;

     private readonly Func<T,bool> _canExecuteMethod = null;

     public DeletgateCommand(Action<T> executeMethod)

         this(executeMethod, null)

     { }

     public DeletgateCommand(Action<T> executeMethod, Func<T,bool> canExecuteMethod) 

     {

         if (executeMethod == null)

             throw new ArgumentNullException("executeMetnod");

         _executeMethod = executeMethod;

         _canExecuteMethod = canExecuteMethod;

     }

     #region ICommand 成员

     /// <summary>

     ///  Method to determine if the command can be executed

     /// </summary>

     public bool CanExecute(T parameter)

     {

         if (_canExecuteMethod != null)

         {

             return _canExecuteMethod(parameter);

         }

         return true;

     }

     /// <summary>

     ///  Execution of the command

     /// </summary>

     public void Execute(T parameter)

     {

         if (_executeMethod != null)

         {

             _executeMethod(parameter);

         }

     }

     #endregion

     event EventHandler ICommand.CanExecuteChanged

     {

         add { CommandManager.RequerySuggested += value; }

         remove { CommandManager.RequerySuggested -= value; }

     }

     #region ICommand 成员

     public bool CanExecute(object parameter)

     {

         if (parameter == null && typeof(T).IsValueType)

         {

             return (_canExecuteMethod == null);

         }

         

         return CanExecute((T)parameter);

     }

     public void Execute(object parameter)

     {

         Execute((T)parameter);

     }

     #endregion

 }

4、ViewModwl层,为了简化,此处Add方法采用硬编码的形式

public class CalculatorViewModel

 {

     CauculatorModel calculatorModel;

     private DeletgateCommand<string> addCommand;

     

     public CalculatorViewModel()

     {

         calculatorModel = new CauculatorModel();

     }

     #region Public Properties

     public string FirstOperand

     {

         get {  return calculatorModel.FirstOperand;  }

         set { calculatorModel.FirstOperand = value;  }

     }

     public string SecondOperand

     {

         get return calculatorModel.SecondOperand; }

         set { calculatorModel.SecondOperand = value; }

     }

     public string Operation

     {

         get return calculatorModel.Operation; }

         set { calculatorModel.Operation = value; }

     }

     public string Result

     {

         get return calculatorModel.Result; }

         set { calculatorModel.Result = value; }

     }

     #endregion

     public ICommand AddCommand

     {

         get

         {

             if (addCommand == null)

             {

                 addCommand = new DeletgateCommand<string>(Add, CanAdd);

             }

             return addCommand;

         }

     }

        

     public  void Add(string x)

     {

         FirstOperand = x;

         SecondOperand = x;

         Result = (double.Parse(FirstOperand) + double.Parse(SecondOperand)).ToString();

         Operation = "+";

         MessageBox.Show( FirstOperand+ Operation +SecondOperand +"=" + Result);

     }

     private static bool CanAdd(string num)

     {

         return true;

     }

 }

ViewModelBase中的代码:

public abstract class ViewModelBase : INotifyPropertyChanged

 {

     public event PropertyChangedEventHandler PropertyChanged;

     protected void OnPropertyChanged(string propertyName)

     {

         PropertyChangedEventHandler handler = PropertyChanged;

         if (handler != null)

         {

             handler(thisnew PropertyChangedEventArgs(propertyName));

         }

     }

 }

5、View层

<Grid>   

       <TextBox  Height="23" Margin="12,63,0,0" Name="textBox1" VerticalAlignment="Top" HorizontalAlignment="Left"  Width="120" />

       <Label Margin="12,25,95,0" Name="label2" Height="32" VerticalAlignment="Top">请输入x的值! x+x=? </Label>

       <Button Height="23" Command="{Binding AddCommand}"

               CommandParameter="{Binding ElementName=textBox1,Path=Text}"   HorizontalAlignment="Left" Margin="12,102,0,0" Name="button1" VerticalAlignment="Top" Width="75">

           确定</Button>

   </Grid>

CommandParameter里传递的是一个参数,当然可以传递多个参数。

MVVM MVC的更多相关文章

  1. MVP MVVM MVC

    上一篇得到大家的关注,非常感谢.由于自己对于这些模式的理解也是有限,对于MVC,MVP,MVVM这些模式的比较,是结合自己的理解,一些地方不一定准确,需要的朋友可以参考下 上一篇得到大家的关注,非常感 ...

  2. 转: GUI应用程序架构的十年变迁:MVC,MVP,MVVM,Unidirectional,Clean

    十年前,Martin Fowler撰写了 GUI Architectures 一文,至今被奉为经典.本文所谈的所谓架构二字,核心即是对于对于富客户端的 代码组织/职责划分 .纵览这十年内的架构模式变迁 ...

  3. Extjs6官方文档译文——应用架构简介(MVC,MVVM)

    应用架构简介 Extjs 同时提供对于MVC和MVVM应用架构的支持.这两个架构方式共享某些概念,而且都旨在沿着逻辑层面划分应用程序代码.每种方法在选择如何划分应用组件上都有其各自的优势. 本指南的目 ...

  4. [ExtJS5学习笔记]第九节 Extjs5的mvc与mvvm框架结构简介

    本文地址:http://blog.csdn.net/sushengmiyan/article/details/38537431 本文作者:sushengmiyan ------------------ ...

  5. MVC,MVP,MVVM区别联系

    本质上都是MVC,MVC在不同技术中的应用衍生出MVP,MVVM MVC:b/s MVP:c/s,尤其winform MVVM:wpf http://www.codeproject.com/Artic ...

  6. 浅谈MVC和MVVM模式

    MVC I’m dating with a model… and a view, and a controller. 众所周知,MVC 是开发客户端最经典的设计模式,iOS 开发也不例外,但是 MVC ...

  7. 架构模式:MVC与MVVM

    本文探讨如下几个问题: 什么是MVC 什么是MVVM MVC与MVVM对架构属性的影响 MVC实例SpringMVC MVVM实例Vue MVC.MVVM与Layer中的Model,Controlle ...

  8. GUI应用程序架构的十年变迁:MVC,MVP,MVVM,Unidirectional,Clean

    十年前,Martin Fowler撰写了 GUI Architectures 一文,至今被奉为经典.本文所谈的所谓架构二字,核心即是对于对于富客户端的 代码组织/职责划分 .纵览这十年内的架构模式变迁 ...

  9. [ExtJS5学习笔记]第九节 Extjs5的mvc与mvvm框架结构简单介绍

    本文地址:http://blog.csdn.net/sushengmiyan/article/details/38537431 本文作者:sushengmiyan ------------------ ...

随机推荐

  1. Angular.js路由 简单小案例

    代码案例: <html> <head> <meta charset="utf-8"> <title>AngularJS 路由实例&l ...

  2. 机器学习实战笔记-7-AdaBoost元算法

    AdaBoost(Adaptive boosting)元算法 元算法:将不同分类器组合起来的结果,也叫集成方法. AdaBoost优点:泛化错误率,易编码,可应用在大部分分类器,无参数调整:缺点:对离 ...

  3. python学习那点事---pycharm使用弹框问题如何解决

    学习python的目标:年后可以找一份不错的维护工作. 2019.11.4日是第一天开始学习python,从开始安装python3.6版本和pycharm开始.安装python版本非常顺利的就完成了, ...

  4. struts框架的一些注意点

    1.Struts.xml文件中<include file="">标签的运用 用法:此标签引用配置文件,Struts2提供了一个默认的struts.xml文件,当此配置文 ...

  5. Little Sub and Mr.Potato's Math Problem (构造法)

    题目传送门Little Sub and Mr.Potato's Math Problem Time Limit: 2 Seconds      Memory Limit: 65536 KB Littl ...

  6. BUUCTF--reverse3

    测试文件:https://buuoj.cn/files/aa4f6c7e8d5171d520b95420ee570e79/a9d22a0e-928d-4bb4-8525-e38c9481469e.ra ...

  7. 20191108PHP数组查找练习

    <?php $arr=[20,30,60]; $new=array(22,"tom"=>33); echo $arr[2]; echo $new['tom']; for ...

  8. 使用纯php构建一个简单的PHP服务器

    使用原生PHP构建一个简单的PHPWeb服务器 1.目录机构 webserver --src -- Response.php -- Server.php -- Request.php -- vendo ...

  9. 03.LNMP架构-PHP源码包编译部署详细步骤

    一.环境准备 操作系统:CentOS_Server_7.5_x64_1804.iso 部署组件:yasm+libmcrypt+libvpx+tiff+libpng+freetype+jpeg+libg ...

  10. 一、Api

    一. private static readonly IList<string> BaseParamKey = new List<string>() { "apiId ...