1. MVVM介绍:

MVVM就是: Model -- 模型(现实中对象的抽象)

View -- UI(用户界面)

       ViewModel -- UI界面的抽象(给View提供数据,并响应View的操作)

2. 关键是要能准确的进行ViewModel的建模,处理好View与ViewModel之间的关系

2.1. 只有2种关系:

数据传递 --- 双向,使用Binding实现;

操作传递 --- 单向(只从View传递给ViewModel),使用命令Command实现;

3. 开始

3.1. 首先创建NotificationObject,它是所以ViewModel的基类

因为要使用Binding,而ViewModel就充当数据源的角色,而要实现当值有变化时会自动响应,就必须实现INotifyPropertyChanged接口,代码如下:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7.  
  8. namespace MVVMTest.ViewModels
  9. {
  10. public class NotificationObject:INotifyPropertyChanged
  11. {
  12. public event PropertyChangedEventHandler PropertyChanged;
  13.  
  14. public void RaisePropertyChanged(string property)
  15. {
  16. if (this.PropertyChanged != null)
  17. this.PropertyChanged.Invoke(this, new PropertyChangedEventArgs(property));
  18.  
  19. }
  20. }
  21. }

3.2.接着要创建DelegateCommand,实现了ICommand接口,用来处理View发送到ViewModel的命令,代码如下:

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using System.Threading.Tasks;
  6. using System.Windows.Input;
  7.  
  8. namespace MVVMTest.Commands
  9. {
  10. public class DelegateCommand:ICommand
  11. {
  12. public bool CanExecute(object parameter)
  13. {
  14. if (this.CanExecuteFunc == null)
  15. {
  16. return true;
  17. }
  18.  
  19. return this.CanExecuteFunc(parameter);
  20. }
  21.  
  22. public event EventHandler CanExecuteChanged;
  23.  
  24. public void Execute(object parameter)
  25. {
  26. if (this.ExecuteAction == null)
  27. {
  28. return;
  29. }
  30. this.ExecuteAction(parameter);
  31. }
  32.  
  33. public Action<object> ExecuteAction { get; set; }
  34. public Func<object, bool> CanExecuteFunc { get; set; }
  35. }
  36. }

3.3.为了方便开发,这里推荐自定义一个code snippet(代码块):

放到此目录下C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC#\Snippets\1033\Visual C#

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <CodeSnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  3. <CodeSnippet Format="1.0.0">
  4. <Header>
  5. <Title>propn</Title>
  6. <Shortcut>propn</Shortcut>
  7. <Description>Code snippet for NotificationObject property and backing field</Description>
  8. <Author>Microsoft Corporation</Author>
  9. <SnippetTypes>
  10. <SnippetType>Expansion</SnippetType>
  11. </SnippetTypes>
  12. </Header>
  13. <Snippet>
  14. <Declarations>
  15. <Literal>
  16. <ID>type</ID>
  17. <ToolTip>Property type</ToolTip>
  18. <Default>int</Default>
  19. </Literal>
  20. <Literal>
  21. <ID>property</ID>
  22. <ToolTip>Property name</ToolTip>
  23. <Default>MyProperty</Default>
  24. </Literal>
  25. <Literal>
  26. <ID>field</ID>
  27. <ToolTip>The variable backing this property</ToolTip>
  28. <Default>myVar</Default>
  29. </Literal>
  30. </Declarations>
  31. <Code Language="csharp"><![CDATA[private $type$ $field$;
  32.  
  33. public $type$ $property$
  34. {
  35. get { return $field$;}
  36. set {
  37. $field$ = value;
  38. this.RaisePropertyChanged("$property$");
  39. }
  40. }
  41. $end$]]>
  42. </Code>
  43. </Snippet>
  44. </CodeSnippet>
  45. </CodeSnippets>

3.4. 由于这个例子较简单,所以没有设计到Model的设计,而直接到ViewModel的设计,一般的规则是每个View就有一个对应的ViewModel,而ViewModel是充当View的数据源的,所以只需要考虑View需要什么数据、含有哪些操作,创建MainWindow的ViewModel,MainWindowViewModel,代码如下:

  1. using MVVMTest.Commands;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7.  
  8. namespace MVVMTest.ViewModels
  9. {
  10. public class MainWindowViewModel:NotificationObject
  11. {
  12. private string txt1;
  13.  
  14. public string Txt1
  15. {
  16. get { return txt1; }
  17. set
  18. {
  19. txt1 = value;
  20. this.RaisePropertyChanged("Txt1");
  21. }
  22. }
  23.  
  24. private string txt2;
  25.  
  26. public string Txt2
  27. {
  28. get { return txt2; }
  29. set
  30. {
  31. txt2 = value;
  32. this.RaisePropertyChanged("Txt2");
  33. }
  34. }
  35.  
  36. private string result;
  37.  
  38. public string Result
  39. {
  40. get { return result; }
  41. set
  42. {
  43. result = value;
  44. this.RaisePropertyChanged("Result");
  45. }
  46. }
  47.  
  48. public DelegateCommand ConcatCommand { get; set; }
  49. public void Concat(object parameter)
  50. {
  51. Result = Txt1 + " and " + Txt2;
  52. }
  53.  
  54. public MainWindowViewModel()
  55. {
  56. ConcatCommand = new DelegateCommand();
  57. ConcatCommand.ExecuteAction = new Action<object>(Concat);
  58. }
  59.  
  60. }
  61. }

3.4.将ViewModel作为数据源赋值给View的DataContext

  1. using MVVMTest.ViewModels;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Text;
  6. using System.Threading.Tasks;
  7. using System.Windows;
  8. using System.Windows.Controls;
  9. using System.Windows.Data;
  10. using System.Windows.Documents;
  11. using System.Windows.Input;
  12. using System.Windows.Media;
  13. using System.Windows.Media.Imaging;
  14. using System.Windows.Navigation;
  15. using System.Windows.Shapes;
  16.  
  17. namespace MVVMTest
  18. {
  19. /// <summary>
  20. /// Interaction logic for MainWindow.xaml
  21. /// </summary>
  22. public partial class MainWindow : Window
  23. {
  24. public MainWindow()
  25. {
  26. InitializeComponent();
  27. this.DataContext = new MainWindowViewModel();
  28. }
  29. }
  30. }

3.5.在View中绑定数据:

  1. <Window x:Class="MVVMTest.MainWindow"
  2. xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  3. xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
  4. Title="MainWindow" Height="" Width="">
  5. <Grid>
  6. <TextBox Margin="40,51,311,216" Text="{Binding Txt1}"/>
  7. <TextBox Margin="230,51,114,216" Text="{Binding Txt2}"/>
  8. <TextBox Margin="128,152,176,139" Text="{Binding Result}"/>
  9. <Button Margin="313,241,64,23" Command="{Binding ConcatCommand}"/>
  10. </Grid>
  11. </Window>

源代码:http://yunpan.cn/c3c7AAXm4U2dP  访问密码 8788

WPF简单MVVM实现的更多相关文章

  1. 从0到1:使用Caliburn.Micro(WPF和MVVM)开发简单的计算器

    从0到1:使用Caliburn.Micro(WPF和MVVM)开发简单的计算器 之前时间一直在使用Caliburn.Micro这种应用了MVVM模式的WPF框架做开发,是时候总结一下了. Calibu ...

  2. .NET CORE(C#) WPF简单菜单MVVM绑定

    微信公众号:Dotnet9,网站:Dotnet9,问题或建议:请网站留言, 如果对您有所帮助:欢迎赞赏. .NET CORE(C#) WPF简单菜单MVVM绑定 阅读导航 本文背景 代码实现 本文参考 ...

  3. WPF 微信 MVVM 【续】发送部分QQ表情

    今天主要记录的就是发送QQ表情, WPF 微信 MVVM里写了,后期为了发送QQ表情,需要把TextBox替换为RichTextBox,接下来就说说替换的过程. 一.支持Binding的RichTex ...

  4. CleanAOP实战系列--WPF中MVVM自动更新

    CleanAOP实战系列--WPF中MVVM自动更新 作者: 立地 邮箱: jarvin_g@126.com QQ: 511363759 CleanAOP介绍:https://github.com/J ...

  5. WPF Prism MVVM 中 弹出新窗体. 放入用户控件

    原文:WPF Prism MVVM 中 弹出新窗体. 放入用户控件 版权声明:本文为博主原创文章,未经博主允许不得转载. https://blog.csdn.net/qq_37214567/artic ...

  6. WPF之MVVM模式(3)

    有种想写一个MVVM框架的冲动!!! 1.Model中的属性应不应该支持OnPropertyChanged事件? 不应该.应该有ViewModel对该属性进行封装,由ViewModel提供OnProp ...

  7. 【WPF】MVVM模式的3种command

    原文:[WPF]MVVM模式的3种command 1.DelegateCommand 2.RelayCommand 3.AttachbehaviorCommand 因为MVVM模式适合于WPF和SL, ...

  8. WPF和MVVM的结合使用方法,不可错过

    Model:存储数据模型(类) 也在此业务逻辑,主要负责类文件的存储. ViewModel:连接View和Model,借助Command来负责界面的跳转和调用Model中方法来操作Model的数据. ...

  9. WPF使用MVVM(一)-属性绑定

    WPF使用MVVM(一)-属性绑定 简单介绍MVVM MVVM是Model(数据类型),View(界面),ViewModel(数据与界面之间的桥梁)的缩写,是一种编程模式,优点一劳永逸,初步增加一些逻 ...

随机推荐

  1. Android-封装JSON数据(JSON对象/JSON数组)

    Android-封装JSON数据(JSON对象/JSON数组),一般情况下不会在Android端封装JSON的数据,因为封装JSON的数据是在服务器端进行封装了,Android更多的工作是解析(JSO ...

  2. IDEA配置spring

    大半天都在看spring,以前总是看不下去,这次慢慢来,慢慢看. 看那些基础的,倒是还不错.好多都是关于helloworld的,写完helloworld,觉得不怎么形象.于是写了动物,作为接口. (1 ...

  3. C#冒泡排序(完整代码)

    百度百科 冒泡排序是笔试面试经常考的内容,虽然它是这些算法里排序速度最慢的 原理:从头开始,每一个元素和它的下一个元素比较,如果它大,就将它与比较的元素交换,否则不动. 这意味着,大的元素总是在向后慢 ...

  4. dockerfile构建redis

    -------------------------------------------------------------

  5. django系列8.5--使用装饰器(视图函数中)实现用户登录状态检验

    views.py def session_auth(fn): def inner(request,*args,**kwargs): status = request.session.get('sess ...

  6. 【SSH学习笔记】用Struts2实现简单的用户登录

    准备阶段 在使用学习Struts2的时候首先要下载相应的架包 Struts2资源下载 这里建议下载第一个,在struts-2.5.14.1-all.zip里有很多实用的东西,不仅有架包还有官方为开发者 ...

  7. 就这么简单!构建强大的WebShell防护体系

    接触web安全中,例如上传一句话WebShell实现上传文件的功能,再通过上传的多功能WebShell,执行病毒文件最终创建远程连接账号,达到入侵目标服务器的效果.我们可以看到,webshell在整个 ...

  8. Jquery选择器 选择一个不存在的元素 为什么不会返回 false

    不管找没找到,$()函数都会返回一个jquery对象,这个jquery对象有个length属性,表示找到多少个匹配的DOM元素,为0就是没找到.

  9. [Objective-C语言教程]内存管理(36)

    内存管理是任何编程语言中最重要的过程之一.它是在需要时分配对象的内存并在不再需要时取消分配的过程. 管理对象内存是一个性能问题; 如果应用程序不释放不需要的对象,则应用程序会因内存占用增加并且性能受损 ...

  10. 哈弗曼树的理解和实现(Java)

    哈弗曼树概述 哈弗曼树又称最优树,是一种带权路径长度最短的树,在实际中有广泛的用途.哈弗曼树的定义,涉及路径.路径长度.权等概念.哈弗曼树可以用于哈弗曼编码,用于压缩,用于密码学等. 哈弗曼树的一些定 ...