在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. 用maven给SpringBoot项目打包

    注意要点: 1.注意某个moule有依赖需要在对应的pom.xml里填写有关的信息,如: <dependencies> <dependency> <artifactId& ...

  2. Openstack_SQLAlchemy 修改数据库的表结构

    目录 目录 前言 更改数据库的方法 为数据库添加一张或多张新表 删除一张或多张表 为旧表添加一个字段 为旧表更新一个字段 为旧表初始化一条新的记录 最后 前言 SQLAlchemy 的使用方法和相关基 ...

  3. http代理工具delphi源码

    http://www.caihongnet.com/content/xingyexinwen/2013/0721/730.html http代理工具delphi源码 以下代码在 DELPHI7+IND ...

  4. 16/8/23-jQuery子调用匿名函数

    通过创建一个自调用匿名函数,创建一个特殊的函数作用域,该作用域中的代码不会和已有的同名函数.方法和变量以及第三方库冲突. 自调用匿名函数写法 方法一: (function(){ //... })(); ...

  5. 【Unity 系统知识】 Time类

    [转载请注明出处] //表示时间总量Time.time:(只读)表示从程序运行的总时间,会随着游戏的暂停而停止计算.Time.unscaledTime:(只读)不考虑timescale对时间修改的总时 ...

  6. Spring MVC处理

    1.首先,用户发送请求,DispatcherServlet会拦截请求,但DispatcherServlet收到请求后不进行处理,而对URL进行解析得到相应的URI(资源标识符). 2.Dispatch ...

  7. (1)leetcode刷题Python笔记——两数之和

    题目如下: 给定一个整数数组 nums 和一个目标值 target,请你在该数组中找出和为目标值的那 两个 整数,并返回他们的数组下标. 你可以假设每种输入只会对应一个答案.但是,你不能重复利用这个数 ...

  8. 利用Lua实现二叉查找树并进行各种遍历

    -- author : coder_zhang-- date : 2014-6-25 root = nil function insert_node(number) if root == nil th ...

  9. poj2385 Apple Catching (线性dp)

    题目传送门 Apple Catching Apple Catching Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 154 ...

  10. python学习第四天基本数据类型 int,string,bool

    python跟其他编程语言一样,拥有基本的数据类型,计算机 只能识别0101,python是解释语言,有其他的解释器 python整型 int a=10 type(a) "int| pyth ...