C# WPF入门学习主线篇(三十一)—— MVVM模式简介

2024-06-14 17:36

本文主要是介绍C# WPF入门学习主线篇(三十一)—— MVVM模式简介,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

C# WPF入门学习主线篇(三十一)—— MVVM模式简介

在这里插入图片描述

MVVM(Model-View-ViewModel)模式是WPF开发中的一种重要架构模式。它通过将用户界面(View)与业务逻辑和数据(Model)分离,提高了代码的可维护性和可测试性。本文将详细介绍MVVM模式的基本概念、组件及其交互方式。

一、MVVM模式的基本概念

1. Model

Model表示应用程序的核心数据和业务逻辑。它通常包含数据结构、业务规则和数据访问代码。Model不依赖于UI,是独立且可重用的组件。例如,在一个员工管理系统中,Model可以表示员工的实体类:

public class Employee
{public string Name { get; set; }public int Age { get; set; }public string Position { get; set; }
}

2. View

View表示用户界面,负责显示数据和接收用户输入。View通过数据绑定和命令与ViewModel交互,而不直接访问Model。View通常是XAML文件及其相关的代码隐藏文件。

<Window x:Class="WpfApp.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Title="MVVM Demo" Height="200" Width="300"><Grid><StackPanel><TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" FontSize="16" Margin="10"/><TextBox Text="{Binding Age, UpdateSourceTrigger=PropertyChanged}" FontSize="16" Margin="10"/><TextBox Text="{Binding Position, UpdateSourceTrigger=PropertyChanged}" FontSize="16" Margin="10"/></StackPanel></Grid>
</Window>

3. ViewModel

ViewModel是View和Model之间的桥梁。它负责从Model获取数据,并将这些数据提供给View,同时处理用户在View上的交互。ViewModel通常实现通知机制(如INotifyPropertyChanged接口),以便在数据变化时通知View进行更新。

using System.ComponentModel;public class EmployeeViewModel : INotifyPropertyChanged
{private Employee _employee;public EmployeeViewModel(){_employee = new Employee { Name = "John Doe", Age = 30, Position = "Software Developer" };}public string Name{get => _employee.Name;set{if (_employee.Name != value){_employee.Name = value;OnPropertyChanged(nameof(Name));}}}public int Age{get => _employee.Age;set{if (_employee.Age != value){_employee.Age = value;OnPropertyChanged(nameof(Age));}}}public string Position{get => _employee.Position;set{if (_employee.Position != value){_employee.Position = value;OnPropertyChanged(nameof(Position));}}}public event PropertyChangedEventHandler PropertyChanged;protected void OnPropertyChanged(string propertyName){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}
}

4. 绑定ViewModel到View

在View的代码隐藏文件中,我们将ViewModel实例绑定到View的DataContext。

using System.Windows;namespace WpfApp
{public partial class MainWindow : Window{public MainWindow(){InitializeComponent();this.DataContext = new EmployeeViewModel();}}
}

二、MVVM模式的优点

1. 提高代码的可维护性

通过将UI和业务逻辑分离,MVVM模式使得代码更加清晰,易于维护和修改。

2. 提高代码的可测试性

业务逻辑集中在ViewModel中,可以方便地进行单元测试,而不依赖于UI。

3. 提高代码的可重用性

Model和ViewModel是独立于UI的,可以在不同的应用程序中重用。

4. 支持设计和开发的分离

开发人员可以专注于ViewModel和Model的开发,而设计人员可以独立于开发人员设计UI。

三、MVVM模式的实现细节

1. 数据绑定

数据绑定是MVVM模式的核心。通过数据绑定,View可以自动从ViewModel中获取数据并显示在UI上。

2. 通知机制

通知机制(如INotifyPropertyChanged接口)使得ViewModel可以在数据变化时通知View更新UI。

3. 命令绑定

命令绑定使得ViewModel可以处理用户在View上的交互,而不需要在View中编写处理逻辑。

using System;
using System.Windows.Input;public class RelayCommand : ICommand
{private readonly Action<object> _execute;private readonly Func<object, bool> _canExecute;public RelayCommand(Action<object> execute, Func<object, bool> canExecute = null){_execute = execute;_canExecute = canExecute;}public bool CanExecute(object parameter) => _canExecute == null || _canExecute(parameter);public void Execute(object parameter) => _execute(parameter);public event EventHandler CanExecuteChanged{add => CommandManager.RequerySuggested += value;remove => CommandManager.RequerySuggested -= value;}
}

在ViewModel中使用命令:

public class EmployeeViewModel : INotifyPropertyChanged
{private Employee _employee;public EmployeeViewModel(){_employee = new Employee { Name = "John Doe", Age = 30, Position = "Software Developer" };UpdateCommand = new RelayCommand(UpdateEmployee);}public string Name{get => _employee.Name;set{if (_employee.Name != value){_employee.Name = value;OnPropertyChanged(nameof(Name));}}}public int Age{get => _employee.Age;set{if (_employee.Age != value){_employee.Age = value;OnPropertyChanged(nameof(Age));}}}public string Position{get => _employee.Position;set{if (_employee.Position != value){_employee.Position = value;OnPropertyChanged(nameof(Position));}}}public ICommand UpdateCommand { get; }private void UpdateEmployee(object parameter){Name = "Updated Name";Age = 35;Position = "Updated Position";}public event PropertyChangedEventHandler PropertyChanged;protected void OnPropertyChanged(string propertyName){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}
}

在View中绑定命令:

<Button Content="Update" Command="{Binding UpdateCommand}" FontSize="16" Margin="10"/>

四、总结

MVVM模式是WPF开发中的一种重要架构模式,通过将用户界面(View)与业务逻辑和数据(Model)分离,提高了代码的可维护性和可测试性。本文介绍了MVVM模式的基本概念、组件及其交互方式,并通过一个简单的示例演示了如何在WPF应用程序中实现MVVM模式。

通过MVVM模式,我们可以提高WPF应用程序的开发效率和代码质量,使得应用程序更加易于维护和扩展。希望本文能帮助你更好地理解和应用MVVM模式,提高WPF开发的水平。

这篇关于C# WPF入门学习主线篇(三十一)—— MVVM模式简介的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1061065

相关文章

HarmonyOS学习(七)——UI(五)常用布局总结

自适应布局 1.1、线性布局(LinearLayout) 通过线性容器Row和Column实现线性布局。Column容器内的子组件按照垂直方向排列,Row组件中的子组件按照水平方向排列。 属性说明space通过space参数设置主轴上子组件的间距,达到各子组件在排列上的等间距效果alignItems设置子组件在交叉轴上的对齐方式,且在各类尺寸屏幕上表现一致,其中交叉轴为垂直时,取值为Vert

Ilya-AI分享的他在OpenAI学习到的15个提示工程技巧

Ilya(不是本人,claude AI)在社交媒体上分享了他在OpenAI学习到的15个Prompt撰写技巧。 以下是详细的内容: 提示精确化:在编写提示时,力求表达清晰准确。清楚地阐述任务需求和概念定义至关重要。例:不用"分析文本",而用"判断这段话的情感倾向:积极、消极还是中性"。 快速迭代:善于快速连续调整提示。熟练的提示工程师能够灵活地进行多轮优化。例:从"总结文章"到"用

Spring Security 从入门到进阶系列教程

Spring Security 入门系列 《保护 Web 应用的安全》 《Spring-Security-入门(一):登录与退出》 《Spring-Security-入门(二):基于数据库验证》 《Spring-Security-入门(三):密码加密》 《Spring-Security-入门(四):自定义-Filter》 《Spring-Security-入门(五):在 Sprin

【前端学习】AntV G6-08 深入图形与图形分组、自定义节点、节点动画(下)

【课程链接】 AntV G6:深入图形与图形分组、自定义节点、节点动画(下)_哔哩哔哩_bilibili 本章十吾老师讲解了一个复杂的自定义节点中,应该怎样去计算和绘制图形,如何给一个图形制作不间断的动画,以及在鼠标事件之后产生动画。(有点难,需要好好理解) <!DOCTYPE html><html><head><meta charset="UTF-8"><title>06

学习hash总结

2014/1/29/   最近刚开始学hash,名字很陌生,但是hash的思想却很熟悉,以前早就做过此类的题,但是不知道这就是hash思想而已,说白了hash就是一个映射,往往灵活利用数组的下标来实现算法,hash的作用:1、判重;2、统计次数;

2. c#从不同cs的文件调用函数

1.文件目录如下: 2. Program.cs文件的主函数如下 using System;using System.Collections.Generic;using System.Linq;using System.Threading.Tasks;using System.Windows.Forms;namespace datasAnalysis{internal static

在JS中的设计模式的单例模式、策略模式、代理模式、原型模式浅讲

1. 单例模式(Singleton Pattern) 确保一个类只有一个实例,并提供一个全局访问点。 示例代码: class Singleton {constructor() {if (Singleton.instance) {return Singleton.instance;}Singleton.instance = this;this.data = [];}addData(value)

C#实战|大乐透选号器[6]:实现实时显示已选择的红蓝球数量

哈喽,你好啊,我是雷工。 关于大乐透选号器在前面已经记录了5篇笔记,这是第6篇; 接下来实现实时显示当前选中红球数量,蓝球数量; 以下为练习笔记。 01 效果演示 当选择和取消选择红球或蓝球时,在对应的位置显示实时已选择的红球、蓝球的数量; 02 标签名称 分别设置Label标签名称为:lblRedCount、lblBlueCount

零基础学习Redis(10) -- zset类型命令使用

zset是有序集合,内部除了存储元素外,还会存储一个score,存储在zset中的元素会按照score的大小升序排列,不同元素的score可以重复,score相同的元素会按照元素的字典序排列。 1. zset常用命令 1.1 zadd  zadd key [NX | XX] [GT | LT]   [CH] [INCR] score member [score member ...]

【机器学习】高斯过程的基本概念和应用领域以及在python中的实例

引言 高斯过程(Gaussian Process,简称GP)是一种概率模型,用于描述一组随机变量的联合概率分布,其中任何一个有限维度的子集都具有高斯分布 文章目录 引言一、高斯过程1.1 基本定义1.1.1 随机过程1.1.2 高斯分布 1.2 高斯过程的特性1.2.1 联合高斯性1.2.2 均值函数1.2.3 协方差函数(或核函数) 1.3 核函数1.4 高斯过程回归(Gauss