一个简单的WPF MVVM实例【转载】

摘要:
[csharp]viewplaincopyusingSystem.ComponentModel;namespaceWPFMVVMExample.Model{publicclassStudentModel:INotifyPropertyChanged{//////学号///privateintstudentId;publicintStudentId{get{returnstudentId;}set{studentId=value;NotifyPropertyChanged;}}//////姓名///privatestringstudentName;publicstringStudentName{get{returnstudentName;}set{studentName=value;NotifyPropertyChanged;}}//////年龄///privateintstudentAge;publicintStudentAge{get{returnstudentAge;}set{studentAge=value;NotifyPropertyChanged;}}//////Email///privatestringstudentEmail;publicstringStudentEmail{get{returnstudentEmail;}set{studentEmail=value;NotifyPropertyChanged;}}//////性别///privatestringstudentSex;publicstringStudentSex{get{returnstudentSex;}set{studentSex=value;NotifyPropertyChanged;}}publiceventPropertyChangedEventHandlerPropertyChanged;publicvoidNotifyPropertyChanged{if(PropertyChanged!=null){PropertyChanged;}}}}StudentModel类实现了接口INotifyPropertyChanged。当类实现该接口后,便可以向执行绑定的客户端发出某一属性值已更改的通知。3ViewModel实现在ViewModel文件夹下新建类文件StudentViewModel.cs,类文件的详细代码如下所示。=null){CanExecuteChanged;}}}}代码中,除了定义StudentViewModel类外,还定义了DelegateCommand类,该类实现了ICommand接口。ICommand接口中的Execute()方法用于命令的执行,CanExecute()方法用于指示当前命令在目标元素上是否可用,当这种可用性发生改变时便会触发接口中的CanExecuteChanged事件。4MainWindow.xaml实现MainWindow.xaml的界面如下图所示。

引用地址:http://blog.csdn.net/yl2isoft/article/details/20838149

1新建WPF应用程序WPFMVVMExample

程序结构如下图所示。

一个简单的WPF MVVM实例【转载】第1张

2Model实现

在Model文件夹下新建业务类StudentModel(类文件StudentModel.cs),类的详细代码如下所示。

  1. usingSystem.ComponentModel;
  2. namespaceWPFMVVMExample.Model
  3. {
  4. publicclassStudentModel:INotifyPropertyChanged
  5. {
  6. ///<summary>
  7. ///学号
  8. ///</summary>
  9. privateintstudentId;
  10. publicintStudentId
  11. {
  12. get
  13. {
  14. returnstudentId;
  15. }
  16. set
  17. {
  18. studentId=value;
  19. NotifyPropertyChanged("StudentId");
  20. }
  21. }
  22. ///<summary>
  23. ///姓名
  24. ///</summary>
  25. privatestringstudentName;
  26. publicstringStudentName
  27. {
  28. get
  29. {
  30. returnstudentName;
  31. }
  32. set
  33. {
  34. studentName=value;
  35. NotifyPropertyChanged("StudentName");
  36. }
  37. }
  38. ///<summary>
  39. ///年龄
  40. ///</summary>
  41. privateintstudentAge;
  42. publicintStudentAge
  43. {
  44. get
  45. {
  46. returnstudentAge;
  47. }
  48. set
  49. {
  50. studentAge=value;
  51. NotifyPropertyChanged("StudentAge");
  52. }
  53. }
  54. ///<summary>
  55. ///Email
  56. ///</summary>
  57. privatestringstudentEmail;
  58. publicstringStudentEmail
  59. {
  60. get
  61. {
  62. returnstudentEmail;
  63. }
  64. set
  65. {
  66. studentEmail=value;
  67. NotifyPropertyChanged("StudentEmail");
  68. }
  69. }
  70. ///<summary>
  71. ///性别
  72. ///</summary>
  73. privatestringstudentSex;
  74. publicstringStudentSex
  75. {
  76. get
  77. {
  78. returnstudentSex;
  79. }
  80. set
  81. {
  82. studentSex=value;
  83. NotifyPropertyChanged("StudentSex");
  84. }
  85. }
  86. publiceventPropertyChangedEventHandlerPropertyChanged;
  87. publicvoidNotifyPropertyChanged(stringpropertyName)
  88. {
  89. if(PropertyChanged!=null)
  90. {
  91. PropertyChanged(this,newPropertyChangedEventArgs(propertyName));
  92. }
  93. }
  94. }
  95. }

StudentModel类实现了接口INotifyPropertyChanged。当类实现该接口后,便可以向执行绑定的客户端发出某一属性值已更改的通知。

3ViewModel实现

在ViewModel文件夹下新建类文件StudentViewModel.cs,类文件的详细代码如下所示。

  1. usingSystem;
  2. usingSystem.Windows.Input;
  3. usingWPFMVVMExample.Model;
  4. namespaceWPFMVVMExample.ViewModel
  5. {
  6. publicclassStudentViewModel
  7. {
  8. publicDelegateCommandShowCommand{get;set;}
  9. publicStudentModelStudent{get;set;}
  10. publicStudentViewModel()
  11. {
  12. Student=newStudentModel();
  13. ShowCommand=newDelegateCommand();
  14. ShowCommand.ExecuteCommand=newAction<object>(ShowStudentData);
  15. }
  16. privatevoidShowStudentData(objectobj)
  17. {
  18. Student.StudentId=1;
  19. Student.StudentName="tiana";
  20. Student.StudentAge=20;
  21. Student.StudentEmail="8644003248@qq.com";
  22. Student.StudentSex="大帅哥";
  23. }
  24. }
  25. publicclassDelegateCommand:ICommand
  26. {
  27. publicAction<object>ExecuteCommand=null;
  28. publicFunc<object,bool>CanExecuteCommand=null;
  29. publiceventEventHandlerCanExecuteChanged;
  30. publicboolCanExecute(objectparameter)
  31. {
  32. if(CanExecuteCommand!=null)
  33. {
  34. returnthis.CanExecuteCommand(parameter);
  35. }
  36. else
  37. {
  38. returntrue;
  39. }
  40. }
  41. publicvoidExecute(objectparameter)
  42. {
  43. if(this.ExecuteCommand!=null)
  44. {
  45. this.ExecuteCommand(parameter);
  46. }
  47. }
  48. publicvoidRaiseCanExecuteChanged()
  49. {
  50. if(CanExecuteChanged!=null)
  51. {
  52. CanExecuteChanged(this,EventArgs.Empty);
  53. }
  54. }
  55. }
  56. }

代码中,除了定义StudentViewModel类外,还定义了DelegateCommand类,该类实现了ICommand接口。

ICommand接口中的Execute()方法用于命令的执行,CanExecute()方法用于指示当前命令在目标元素上是否可用,当这种可用性发生改变时便会触发接口中的CanExecuteChanged事件。

我们可以将实现了ICommand接口的命令DelegateCommand赋值给Button(命令源)的Command属性(只有实现了ICommandSource接口的元素才拥有该属性),这样Button便与命令进行了绑定。

4MainWindow.xaml实现

MainWindow.xaml的界面如下图所示。

一个简单的WPF MVVM实例【转载】第2张

MainWindow.xaml界面的xaml代码如下所示。

  1. <Windowx:Class="WPFMVVMExample.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="350"Width="525">
  5. <Grid>
  6. <LabelContent="学号"Height="28"HorizontalAlignment="Left"Margin="54,23,0,0"Name="labelStudentId"VerticalAlignment="Top"/>
  7. <TextBoxText="{BindingStudent.StudentId}"IsReadOnly="True"Height="23"HorizontalAlignment="Right"Margin="0,27,289,0"Name="textBoxStudentId"VerticalAlignment="Top"Width="120"/>
  8. <LabelContent="姓名"Height="28"HorizontalAlignment="Left"Margin="54,61,0,0"Name="labelStudentName"VerticalAlignment="Top"/>
  9. <TextBoxText="{BindingStudent.StudentName}"IsReadOnly="True"Height="23"HorizontalAlignment="Left"Margin="94,65,0,0"Name="textBoxStudentName"VerticalAlignment="Top"Width="120"/>
  10. <LabelContent="年龄"Height="28"HorizontalAlignment="Left"Margin="54,94,0,0"Name="labelStudentAge"VerticalAlignment="Top"/>
  11. <TextBoxText="{BindingStudent.StudentAge}"IsReadOnly="True"Height="23"HorizontalAlignment="Left"Margin="94,99,0,0"Name="textBoxStudentAge"VerticalAlignment="Top"Width="120"/>
  12. <LabelContent="Email"Height="28"HorizontalAlignment="Left"Margin="50,138,0,0"Name="labelStudentEmail"VerticalAlignment="Top"/>
  13. <TextBoxText="{BindingStudent.StudentEmail}"IsReadOnly="True"Height="23"HorizontalAlignment="Left"Margin="94,141,0,0"Name="textBoxStudentEmail"VerticalAlignment="Top"Width="120"/>
  14. <LabelContent="性别"Height="28"HorizontalAlignment="Left"Margin="57,176,0,0"Name="labelStudentSex"VerticalAlignment="Top"/>
  15. <TextBoxText="{BindingStudent.StudentSex}"IsReadOnly="True"Height="23"HorizontalAlignment="Left"Margin="94,180,0,0"Name="textBoxStudentSex"VerticalAlignment="Top"Width="120"/>
  16. <ButtonCommand="{BindingShowCommand}"Content="显示"Height="23"HorizontalAlignment="Left"Margin="345,27,0,0"Name="buttonShow"VerticalAlignment="Top"Width="75"/>
  17. </Grid>
  18. </Window>

MainWindow.xaml的后端代码如下所示。

  1. usingSystem.Windows;
  2. usingWPFMVVMExample.ViewModel;
  3. namespaceWPFMVVMExample
  4. {
  5. ///<summary>
  6. ///MainWindow.xaml的交互逻辑
  7. ///</summary>
  8. publicpartialclassMainWindow:Window
  9. {
  10. publicMainWindow()
  11. {
  12. InitializeComponent();
  13. this.DataContext=newStudentViewModel();
  14. }
  15. }
  16. }

5运行程序

运行程序,点击“显示”按钮,即将数据绑定至界面显示。

一个简单的WPF MVVM实例【转载】第3张

6说明

WPF中使用MVVM可以降低UI显示与后端逻辑代码的耦合度,即更换界面时,只需要修改很少的逻辑代码就可以实现,甚至不用修改。

在WinForm开发中,我们一般会直接操作界面的元素(如:TextBox1.Text=“aaa”),这样一来,界面变化后,后端逻辑代码也需要做相应的变更。

在WPF中使用数据绑定机制,当数据变化后,数据会通知界面变更的发生,而不需要通过访问界面元素来修改值,这样在后端逻辑代码中也就不必操作或者很少操作界面的元素了。

使用MVVM,可以很好的配合WPF的数据绑定机制来实现UI与逻辑代码的分离,MVVM中的View表示界面,负责页面显示,ViewModel负责逻辑处理,包括准备绑定的数据和命令,ViewModel通过View的DataContext属性绑定至View,Model为业务模型,供ViewModel使用。

免责声明:文章转载自《一个简单的WPF MVVM实例【转载】》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇centos安装dotnet-sdk-3.1出现no package问题vCenter线上操作磁盘扩容下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

wpf中的全局键

在wpf中的全局键和form中有些差异,所以在这里记录一下,有用到得朋友可以试试! 首先注册APi 代码 1  [DllImport("user32.dll")]2  public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint control, System.Windows.For...

WPF TextBox/TextBlock 文本超出显示时,文本靠右显示

文本框显示 文本框正常显示: 文本框超出区域显示: 实现方案 判断文本框是否超出区域 请见《TextBlock IsTextTrimmed 判断文本是否超出》 设置文本布局显示 1. FlowDirection 当文本超出显示区域时,设置FlowDirection靠右显示 下面是封装的附加属性ScrollEndWhenTextTrimmed 1...

继续聊WPF——用Blend自定义Listview控件的列表头

在Blend中右击ListView控件,从样式和模板相关的菜单项中,我们没找到与列表头有关的项。 然后,我们到属性面板中找GridView的ColumnHeaderContainerStyle属性,结果你发现,就算你在高级选项菜单中把它转换为本地资源,你会发现它没有反应,切换到XAML视图也没看到生成的代码。 那是不是没办法了呢?这个问题我想了想...

如何将WPF browser app 转换成WPF windows application

转载于:http://dotnetframework.blogspot.com.au/2011/01/wpf-browser-application-wpf-windows.html WPF Browser Application 是WPF 中较新的功能。其实它的基本概念,仍然是ClickOnce Application。所以在权限及安控的处理上,必须很小...

使用swiper.js实现移动端tab切换

在项目中遇到的,要实现tab切换,我用的是swiper.js 官网:http://www.swiper.com.cn/api/start/new.html 1 <!DOCTYPE html> 2 <html lang="zh"> 3 <head> 4 <meta charset="UTF-...

AngularJS学习笔记(一) 关于MVVM和双向绑定

写在前面:      因为需要开始学习ng,之前在知乎上听大神们介绍ng的时候说这个坑如何的大,学了一阵(其实也就三天),感觉ng做的很大很全,在合适的情境你可以完全使用ng搞定一切。这一点从诸如jqLite之类的鸡肋就能看出来了。所以搞得ng很大。。     更主要的是,ng用一种和之前完全不同的思维方式去组织代码,它就是Model-View-ViewM...