梦琪小生 【转】【WPF】WPF MVVM 简单实例
1 新建WPF 应用程序WPFMVVMExample
程序结构如下图所示。
2 Model实现
在Model文件夹下新建业务类StudentModel(类文件StudentModel.cs),类的详细代码如下所示。

using System.ComponentModel; namespace WPFMVVMExample.Model
{
public class StudentModel : INotifyPropertyChanged
{
/// <summary>
/// 学号
/// </summary>
private int studentId;
public int StudentId
{
get
{
return studentId;
}
set
{
studentId = value;
NotifyPropertyChanged("StudentId");
}
} /// <summary>
/// 姓名
/// </summary>
private string studentName;
public string StudentName
{
get
{
return studentName;
}
set
{
studentName = value;
NotifyPropertyChanged("StudentName");
}
} /// <summary>
/// 年龄
/// </summary>
private int studentAge;
public int StudentAge
{
get
{
return studentAge;
}
set
{
studentAge = value;
NotifyPropertyChanged("StudentAge");
}
} /// <summary>
/// </summary>
private string studentEmail;
public string StudentEmail
{
get
{
return studentEmail;
}
set
{
studentEmail = value;
NotifyPropertyChanged("StudentEmail");
}
} /// <summary>
/// 性别
/// </summary>
private string studentSex;
public string StudentSex
{
get
{
return studentSex;
}
set
{
studentSex = value;
NotifyPropertyChanged("StudentSex");
}
} public event PropertyChangedEventHandler PropertyChanged;
public void NotifyPropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}

StudentModel类实现了接口INotifyPropertyChanged。当类实现该接口后,便可以向执行绑定的客户端发出某一属性值已更改的通知。
3 ViewModel实现
在ViewModel文件夹下新建类文件StudentViewModel.cs,类文件的详细代码如下所示。

using System;
using System.Windows.Input;
using WPFMVVMExample.Model; namespace WPFMVVMExample.ViewModel
{
public class StudentViewModel
{
public DelegateCommand ShowCommand { get; set; }
public StudentModel Student { get; set; }
public StudentViewModel()
{
Student = new StudentModel();
ShowCommand=new DelegateCommand();
ShowCommand.ExecuteCommand = new Action<object>(ShowStudentData);
}
private void ShowStudentData(object obj)
{
Student.StudentId = 1;
Student.StudentName = "tiana";
Student.StudentAge = 20;
Student.StudentEmail = "8644003248@qq.com";
Student.StudentSex = "大帅哥";
} } public class DelegateCommand : ICommand
{
public Action<object> ExecuteCommand = null;
public Func<object, bool> CanExecuteCommand = null;
public event EventHandler CanExecuteChanged; public bool CanExecute(object parameter)
{
if (CanExecuteCommand != null)
{
return this.CanExecuteCommand(parameter);
}
else
{
return true;
}
} public void Execute(object parameter)
{
if (this.ExecuteCommand != null)
{
this.ExecuteCommand(parameter);
}
} public void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
{
CanExecuteChanged(this, EventArgs.Empty);
}
}
}
}

代码中,除了定义StudentViewModel类外,还定义了DelegateCommand类,该类实现了ICommand接口。
ICommand接口中的Execute()方法用于命令的执行,CanExecute()方法用于指示当前命令在目标元素上是否可用,当这种可用性发生改变时便会触发接口中的CanExecuteChanged事件。
我们可以将实现了ICommand接口的命令DelegateCommand赋值给Button(命令源)的Command属性(只有实现了ICommandSource接口的元素才拥有该属性),这样Button便与命令进行了绑定。
4 MainWindow.xaml实现
MainWindow.xaml的界面如下图所示。
MainWindow.xaml界面的xaml代码如下所示。

<Window x:Class="WPFMVVMExample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<Label Content="学号" Height="28" HorizontalAlignment="Left" Margin="54,23,0,0" Name="labelStudentId" VerticalAlignment="Top" />
<TextBox Text="{Binding Student.StudentId}" IsReadOnly="True" Height="23" HorizontalAlignment="Right" Margin="0,27,289,0" Name="textBoxStudentId" VerticalAlignment="Top" Width="120" />
<Label Content="姓名" Height="28" HorizontalAlignment="Left" Margin="54,61,0,0" Name="labelStudentName" VerticalAlignment="Top" />
<TextBox Text="{Binding Student.StudentName}" IsReadOnly="True" Height="23" HorizontalAlignment="Left" Margin="94,65,0,0" Name="textBoxStudentName" VerticalAlignment="Top" Width="120" />
<Label Content="年龄" Height="28" HorizontalAlignment="Left" Margin="54,94,0,0" Name="labelStudentAge" VerticalAlignment="Top" />
<TextBox Text="{Binding Student.StudentAge}" IsReadOnly="True" Height="23" HorizontalAlignment="Left" Margin="94,99,0,0" Name="textBoxStudentAge" VerticalAlignment="Top" Width="120" />
<Label Content="Email" Height="28" HorizontalAlignment="Left" Margin="50,138,0,0" Name="labelStudentEmail" VerticalAlignment="Top" />
<TextBox Text="{Binding Student.StudentEmail}" IsReadOnly="True" Height="23" HorizontalAlignment="Left" Margin="94,141,0,0" Name="textBoxStudentEmail" VerticalAlignment="Top" Width="120" />
<Label Content="性别" Height="28" HorizontalAlignment="Left" Margin="57,176,0,0" Name="labelStudentSex" VerticalAlignment="Top" />
<TextBox Text="{Binding Student.StudentSex}" IsReadOnly="True" Height="23" HorizontalAlignment="Left" Margin="94,180,0,0" Name="textBoxStudentSex" VerticalAlignment="Top" Width="120" />
<Button Command="{Binding ShowCommand}" Content="显示" Height="23" HorizontalAlignment="Left" Margin="345,27,0,0" Name="buttonShow" VerticalAlignment="Top" Width="75" />
</Grid>
</Window>

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

using System.Windows;
using WPFMVVMExample.ViewModel; namespace WPFMVVMExample
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
this.DataContext = new StudentViewModel();
}
}
}

5 运行程序
运行程序,点击“显示”按钮,即将数据绑定至界面显示。
6 说明
WPF中使用MVVM可以降低UI显示与后端逻辑代码的耦合度,即更换界面时,只需要修改很少的逻辑代码就可以实现,甚至不用修改。
在WinForm开发中,我们一般会直接操作界面的元素(如:TextBox1.Text=“aaa”),这样一来,界面变化后,后端逻辑代码也需要做相应的变更。
在WPF中使用数据绑定机制,当数据变化后,数据会通知界面变更的发生,而不需要通过访问界面元素来修改值,这样在后端逻辑代码中也就不必操作或者很少操作界面的元素了。
使用MVVM,可以很好的配合WPF的数据绑定机制来实现UI与逻辑代码的分离,MVVM中的View表示界面,负责页面显示,ViewModel负责逻辑处理,包括准备绑定的数据和命令,ViewModel通过View的DataContext属性绑定至View,Model为业务模型,供ViewModel使用。
梦琪小生 【转】【WPF】WPF MVVM 简单实例的更多相关文章
- Wpf(Storyboard)动画简单实例
原文:Wpf(Storyboard)动画简单实例 动画的三种变换方式 RotateTransform:旋转变换变化值:CenterX围绕转的圆心横坐标 CenterY纵坐标 Angle旋转角度(角度正 ...
- WPF框架MVVM简单例子
MVVM是Model-View-ViewModel的缩写形式,它通常被用于WPF或Silverlight开发.Model——可以理解为带有字段,属性的类.View——可以理解为我们所看到的UI.Vie ...
- 【转】【WPF】WPF MVVM 简单实例
1 新建WPF 应用程序WPFMVVMExample 程序结构如下图所示. 2 Model实现 在Model文件夹下新建业务类StudentModel(类文件StudentModel.cs),类的详细 ...
- WPF单线程定时器 简单实例
//窗体加载完毕 void MyMessageBox_Loaded(object sender, RoutedEventArgs e) { //启动定时期倒计时,多线程计时 //System.Thre ...
- WPF自学入门(十)WPF MVVM简单介绍
前面文章中,我们已经知道,WPF技术的主要特点是数据驱动UI,所以在使用WPF技术开发的过程中是以数据为核心的,WPF提供了数据绑定机制,当数据发生变化时,WPF会自动发出通知去更新UI. 我们不管 ...
- 从0到1:使用Caliburn.Micro(WPF和MVVM)开发简单的计算器
从0到1:使用Caliburn.Micro(WPF和MVVM)开发简单的计算器 之前时间一直在使用Caliburn.Micro这种应用了MVVM模式的WPF框架做开发,是时候总结一下了. Calibu ...
- WPF自学入门(十一)WPF MVVM模式Command命令 WPF自学入门(十)WPF MVVM简单介绍
WPF自学入门(十一)WPF MVVM模式Command命令 在WPF自学入门(十)WPF MVVM简单介绍中的示例似乎运行起来没有什么问题,也可以进行更新.但是这并不是我们使用MVVM的正确方式 ...
- WPF MVVM简单介绍
前面文章中,我们已经知道,WPF技术的主要特点是数据驱动UI,所以在使用WPF技术开发的过程中是以数据为核心的,WPF提供了数据绑定机制,当数据发生变化时,WPF会自动发出通知去更新UI. 我们不管 ...
- WPF 微信 MVVM 【续】发送部分QQ表情
今天主要记录的就是发送QQ表情, WPF 微信 MVVM里写了,后期为了发送QQ表情,需要把TextBox替换为RichTextBox,接下来就说说替换的过程. 一.支持Binding的RichTex ...
随机推荐
- Python之手把手教你用JS逆向爬取网易云40万+评论并用stylecloud炫酷词云进行情感分析
本文借鉴了@平胸小仙女的知乎回复 https://www.zhihu.com/question/36081767 写在前面: 文章有点长,操作有点复杂,需要代码的直接去文末即可.想要学习的需要有点耐心 ...
- JavaScript学习笔记:你必须要懂的原生JS(二)
11.如何正确地判断this?箭头函数的this是什么? this是 JavaScript 语言的一个关键字.它是函数运行时,在函数体内部自动生成的一个对象,只能在函数体内部使用. this的绑定规则 ...
- springMVC-5-视图解析器
视图和视图解析器工作流程 第一步:获取到ModelAndView对象 请求处理方法执行完成后,无论返回是String,View 还是 ModeMap 类型,Spring MVC 也会在内部将它们装配成 ...
- spring-1-spring介绍和IOC容器开发
一.介绍 1.版本 2.下载(jar包依赖) 下载 所以搜索:https://repo.spring.io/release/org/springframework/spring/ 文件分配 maven ...
- MySQL问题定位-性能优化之我见
前言 首先任何一个数据库不是独立存在的,也不是凭空想象决定出来的. 数据库的架构离不开应用的场景.所以,为了解决某些深入的问题,首先你得掌握数据库的原理与架构.原理掌握得越深入,越能帮助你定位复杂与隐 ...
- 【LeetCode】面试题62. 圆圈中最后剩下的数字
题目:面试题62. 圆圈中最后剩下的数字 这题很有意思,也很巧妙,故记录下来. 官方题解思路,是约瑟夫环的数学解法: 我们将上述问题建模为函数 f(n, m),该函数的返回值为最终留下的元素的序号. ...
- webSocket实现多人聊天功能
webSocket实现多人在线聊天 主要思路如下: 1.使用vue构建简单的聊天室界面 2.基于nodeJs 的webSocket开启一个socket后台服务,前端使用H5的webSocket来创建一 ...
- 用python将word转pdf、doc转docx等
word ==> pdf def doc2pdf(file_path): """ word格式转换doc|docx ==> pdf :return: &quo ...
- SQL SERVER获取某张表创建的索引
1 SELECT 索引名称=a.name 2 ,表名=c.name 3 ,索引字段名=d.name 4 ,索引字段位置=d.colid 5 FROM sysindexes a 6 JOIN sysin ...
- C++利用模板在Windows上快速调用DLL函数
更新日志 --------- 2021/08/01 更新V2.2 增加 GetHmodule 函数 - 允许用户获取HMODULE以验证加载DLL是否成功. 2021/08/03 更新V2.3 增加 ...