一、MVVM简介
MVC Model View Control
MVP
MVVM即Model-View-ViewModel,MVVM模式与MVP(Model-View-Presenter)模式相似,主要目的是分离视图(View)和模型(Model),具有低耦合、可重用性、独立开发、可测试性等优点。

MVVM框架有很多,开源的主要有:
-
MVVM Light Toolkit:有visual Studio和Expression Blend的项目和项的模板。更多信息请看这里,另外可以参考VS和Expression Blend的使用教程。
-
Caliburn Micro:支持视图模型先行(ViewModel-First)和视图先行(View-First)两种开发方式,通过co-routine支持异步编程。
-
Simple MVVM Toolkit:提供VS项目和项的模板,依赖注入,支持深拷贝以及模型和视图模型之间的属性关联。
-
Catel:包含项目和项的模板,用户控件和企业类库。支持动态视图模型注入,视图模型的延迟加载和验证。还支持WP7专用的视图模型服务。
闭源框架主要有:
-
Intersoft ClientUI:付费的,只支持WPF和Silverlight,但是,除了MVVM框架,它还提供其它一些特性。
-
Vidyano:免费但不开源。带有实体映射/虚拟持久化对象(数据容器),业务规则以及内置基于ACL的安全特性。
二、原生版本的MVVM实例

Models 存放的是数据模型
Service存放的是业务逻辑
ViewModels存放的便是视图模型
Views存放WPF窗口
2.1 Models文件夹中创建一个用户模型User.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Wpfmvvm_demo.Models
{
public class User
{
/// <summary>
/// 用户名
/// </summary>
public string? Name { get; set; }
/// <summary>
/// 密码
/// </summary>
public string? Password { get; set; }
}
}
2.2 在Services文件夹中添加用户的业务逻辑UserService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Wpfmvvm_demo.Models;
namespace Wpfmvvm_demo.Services
{
public class UserService
{
/// <summary>
/// 获取所有用户方法
/// </summary>
/// <returns></returns>
public List<User> GetAllUser()
{
List<User> users = new ();
for (int i = 0; i < 3; i++)
{
var user = new User();
user.Name = "用户" + i;
user.Password = "密码" + i;
users.Add(user);
}
return users;
}
}
}
2.3 在ViewModels中创建NotificationObject.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Wpfmvvm_demo.ViewModels
{
public class NotificationObject : INotifyPropertyChanged
{
public event PropertyChangedEventHandler? PropertyChanged;
public void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
{
PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}
}
}
2.4 在ViewModels文件中创建DelegateCommand.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Wpfmvvm_demo.ViewModels
{
public class DelegateCommand : ICommand
{
public event EventHandler? CanExecuteChanged;
public Func<object?,bool>? DoCanExecute { get; set; }
public Action<object?>? DoExecute { get; set; }
public bool CanExecute(object? parameter)
{
if (DoCanExecute != null)
{
return DoCanExecute(parameter);
}
return true;
}
public void Execute(object? parameter)
{
if (DoExecute != nu

最低0.47元/天 解锁文章
2万+

被折叠的 条评论
为什么被折叠?



