在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. MongoDB性能分析

    # mongostat --host=100.150.2.12 --port=27017 --authenticationDatabase=admin --username=root --passwo ...

  2. Vmware 15 新建虚拟机黑屏

    win10 的磁盘大小设置60的倍数 centos 使用 40g

  3. Codeforces 1197 E (dp+sort+二分) (Rust)

    原题链接 2300分 大意 俄罗斯套娃,每个有内容半径in和外围半径out in_i<out_i 如果 in_i >= out_j ,那么j可以放在i内 定义残留空间 = 一列嵌套的套娃 ...

  4. poj2431Expedition

    A group of cows grabbed a truck and ventured on an expedition deep into the jungle. Being rather poo ...

  5. C#将数据写入本地文件

    在平时开发过程中,可能会碰到内网测试没问题,但是更新到外网时会报错,这时我们又无法在外网进行调试.如果我们分析完业务可能产生的问题还是无法得到报错的原因,那么可以在关键的地方加上异常处理,然后将异常或 ...

  6. python参数的介绍

    一.函数1.为什么要使用函数?减少代码的冗余2.函数先定义后使用(相当于变量一样先定义后使用)3.函数的分类:内置函数:python解释器自带的,直接拿来用就行了自定义函数:根据自己的需求自己定义的函 ...

  7. [eclipse相关] 001 - 启动+运行优化

    本随笔参考了其他博客内容,且在验证有效之下才或誊抄或摘录或加上自己经验组合而成. 参考博客: 1,http://zwd596257180.gitee.io/blog/2019/04/17/eclips ...

  8. HashMap和布隆过滤器命中性能测试

    package datafilter; import com.google.common.base.Stopwatch; import com.google.common.hash.BloomFilt ...

  9. vue-router 路由元信息 终于搞明白了路由元信息是个啥了

    vue-router 路由元信息:https://blog.csdn.net/wenyun_kang/article/details/70987840 终于搞明白了路由元信息是个啥了:https:// ...

  10. P2639 [USACO09OCT]Bessie的体重问题Bessie's Weight

    题目传送门 这题和01背包最大的区别在于它没有价值,所以我们可以人工给它赋一个价值,由于要求体积最大,把价值赋成体积即可.顺带一提,这题数据范围很大,二维会MLE,要压缩成一维才可以AC 下面给出参考 ...