WPF中的MVVM设计模式

发布于:2025-06-25 ⋅ 阅读:(23) ⋅ 点赞:(0)

一,什么是MVVM?

 MVVM 是一种设计模式,全称是 Model-View-ViewModel,它的目的是实现 界面与业务逻辑的分离。
它将代码分为三部分:

层次 作用
Model 数据模型层,代表业务逻辑和数据结构,通常是 POCO 类或实体类。
View 视图层,用户界面(例如 XAML 页面)。它只负责展示内容。
ViewModel 视图模型层,负责连接 View 和 Model,是数据绑定的桥梁。

MVVM 的核心思想是:让 UI 自动响应数据变化,而不是写死在代码里

二,MVVM 的核心机制:数据绑定 + 通知机制

1,数据绑定(Data Binding)

 MVVM 的精髓在于:绑定数据,而不是控制 UI。
 通过 WPF/XAML 中的 {Binding},你可以将 UI 控件直接绑定到 ViewModel 的属性上。

<TextBox Text="{Binding UserName}" />

 只要 UserName 属性发生变化,界面就会自动更新。

属性变更通知(INotifyPropertyChanged)

 为了让 UI 能感知属性的变化,ViewModel 通常实现 INotifyPropertyChanged 接口。
标准写法:

public class MyViewModel : INotifyPropertyChanged
{
    private string userName;
    public string UserName
    {
        get => userName;
        set
        {
            if (userName != value)
            {
                userName = value;
                OnPropertyChanged(nameof(UserName));
            }
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName) =>
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}

为了简化重复代码,常常会使用 SetProperty 辅助方法(比如来自 Prism、CommunityToolkit.Mvvm 等库):

protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
    if (Equals(storage, value)) return false;
    storage = value;
    OnPropertyChanged(propertyName);
    return true;
}

三,MVVM各层的职责划分

  • View (视图)
    • 通常是.xaml文件
    • 不包含业务逻辑,仅负责UI展示
    • 通过 DataContext 绑定到 ViewModel。
  • ViewModel(视图模型)
    • 承担 UI 的逻辑。
    • 提供属性、命令(Command)等供绑定。
    • 不知道 View 的具体内容,但知道自己暴露了哪些可以供 UI 使用的功能。
  • Model(模型)
    • 是数据结构、实体类、服务调用逻辑的封装。
    • 完全独立于 UI。

四,手动实现一个SetProperty 和通知

 如果你不想引用 MVVM 框架,可以按以下方式定义一个基础类:

1.创建 BaseViewModel.cs

using System.ComponentModel;
using System.Runtime.CompilerServices;

public class BaseViewModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;
	protected void OnPropertyChanged(string propertyName)
	{
  	  PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
	}

	protected void SetProperty<T>(ref T item, T value, [CallerMemberName] string propertyName = 		null)
	{
 	   if (!EqualityComparer<T>.Default.Equals(item, value)
 	   {
        item = value;
        OnPropertyChanged(propertyName);
   		}
   	}
}

2. ViewModel类继承它

public class MyViewModel : BaseViewModel
{
    private int textBox_TempDelay_;
    public int textBox_TempDelay
    {
        get => textBox_TempDelay_;
        set => SetProperty(ref textBox_TempDelay_, value);
    }
}

五,引入外部库

 使用NuGet包管理器

Install-Package CommunityToolkit.Mvvm
using CommunityToolkit.Mvvm.ComponentModel;

public partial class MyViewModel : ObservableObject
{
    private int textBox_TempDelay_;
    public int textBox_TempDelay
    {
        get => textBox_TempDelay_;
        set => SetProperty(ref textBox_TempDelay_, value);
    }
}

六,总结

 MVVM 模式是现代 UI 应用程序设计的基石,特别适合像 WPF、UWP、MAUI、Xamarin 这类数据绑定驱动的框架。通过明确的层次分离和数据驱动的 UI 机制,开发者可以更轻松地构建复杂而健壮的应用。