C# WPF入门学习主线篇(三十二)—— 创建Model、View和ViewModel

embedded/2024/10/18 7:52:24/

C# WPF入门学习主线篇(三十二)—— 创建Model、View和ViewModel

在这里插入图片描述

在前一篇文章中,我们介绍了MVVM(Model-View-ViewModel)模式的基本概念。本篇将深入探讨如何在实际开发中创建Model、View和ViewModel,并通过一个具体示例来演示它们的交互和实现。

一、创建Model

Model表示应用程序的核心数据和业务逻辑。在MVVM模式中,Model应尽量保持独立,不依赖于UI。以下是一个简单的Model示例:

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

二、创建View

View表示用户界面,通过XAML定义。View与ViewModel通过数据绑定进行交互,而不直接访问Model。以下是一个简单的View示例:

<Window x:Class="WpfApp.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="clr-namespace:WpfApp"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"/><Button Content="Update" Command="{Binding UpdateCommand}" FontSize="16" Margin="10"/></StackPanel></Grid>
</Window>

三、创建ViewModel

ViewModel负责从Model获取数据,并将这些数据提供给View,同时处理用户在View上的交互。ViewModel通常实现INotifyPropertyChanged接口,以便在数据变化时通知View更新UI。

1. 实现INotifyPropertyChanged接口

首先,我们需要一个辅助类来实现命令绑定。以下是一个简单的RelayCommand类:

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;}
}

2. 创建EmployeeViewModel

然后,我们创建一个EmployeeViewModel类来封装Employee数据,并实现数据绑定和命令绑定:

using System.ComponentModel;
using System.Windows.Input;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));}
}

3. 绑定ViewModel到View

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

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

四、完整代码示例

MainWindow.xaml

<Window x:Class="WpfApp.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="clr-namespace:WpfApp"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"/><Button Content="Update" Command="{Binding UpdateCommand}" FontSize="16" Margin="10"/></StackPanel></Grid>
</Window>

MainWindow.xaml.cs

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

Employee.cs

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

EmployeeViewModel.cs

using System.ComponentModel;
using System.Windows.Input;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));}
}

RelayCommand.cs

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;}
}

五、总结

通过本文,我们详细介绍了如何在WPF中创建Model、View和ViewModel,并通过一个具体示例演示了它们的交互和实现。MVVM模式通过将UI和业务逻辑分离,提高了代码的可维护性和可测试性,是WPF开发中的一种重要架构模式。希望本文能帮助你更好地理解和应用MVVM模式,提高WPF开发的水平。


http://www.ppmy.cn/embedded/48588.html

相关文章

B+索引的分裂及选择率和索引基数

1、B树索引的分裂 B树索引页的分裂并不总是从页的中间记录开始&#xff0c;这样可能会导致页空间的浪费。 例子 比如下面这个记录&#xff1a; 1、2、3、4、5、6、7、8、9 由于插入是以自增的顺序进行的&#xff0c;若这时插入第10条记录然后进行页的分裂操作&#xff0c;那…

代码解读 | Hybrid Transformers for Music Source Separation[06]

一、背景 0、Hybrid Transformer 论文解读 1、代码复现|Demucs Music Source Separation_demucs架构原理-CSDN博客 2、Hybrid Transformer 各个模块对应的代码具体在工程的哪个地方 3、Hybrid Transformer 各个模块的底层到底是个啥&#xff08;初步感受&#xff09;&#xff1…

Ceph入门到精通-Crimson 和 Classic Ceph OSD 架构之间的区别

Crimson 和 Classic Ceph OSD 架构之间的区别 在典型的 ceph-osd 架构中,messenger 线程从 wire 读取客户端消息,它将消息放在 OP 队列中。然后,osd-op thread-pool 会提取消息,并创建一个事务并将其排队到 BlueStore,当前的默认 ObjectStore 实现。然后,BlueStore 的 k…

Vue项目中,利用iframe在线预览pdf/图片等

在components下新建 src\components\iFrame\index.vue <template><div v-loading"loading" :style"height: height"><iframe :src"src" frameborder"no" style"width: 100%; height: 100%" scrolling"…

江苏哪些行业需要服务器托管?

服务器托管顾名思义就是用户委托具有完善设备的机房、良好网络和丰富运营经验的服务商管理其计算机系统&#xff0c;使企业的服务器能够更加安全、稳定和高效的运行&#xff0c;那在江苏都有哪些行业需要服务器托管服务呢&#xff1f;本文就来大概介绍一下。 首先让我们来一起了…

u盘数据要在哪台电脑上恢复?u盘数据恢复后保存在哪里

在数字化时代&#xff0c;U盘已成为我们日常生活中不可或缺的数据存储设备。然而&#xff0c;由于各种原因&#xff0c;U盘中的数据可能会意外丢失&#xff0c;这时数据恢复就显得尤为重要。但是&#xff0c;很多人对于在哪台电脑上进行U盘数据恢复以及恢复后的数据应保存在哪里…

Pod中使用自定义服务账号调用自定义资源

一、背景 1、从开发角度 &#xff08;1&#xff09;服务通过容器化部署的方式运行在云环境的Pod中&#xff0c;然而在 Kubernetes 中&#xff0c;Pod 中的服务不能直接通过 client-go 访问 Kubernetes 资源&#xff0c;而是需要通过 Kubernetes API Server 来进行访问。clien…

数据结构——队列(Queue)详解

1.队列&#xff08;Queue&#xff09; 1.1概念 队列&#xff1a;只允许在一端进行插入数据操作&#xff0c;在另一端进行删除数据操作的特殊线性表&#xff0c;队列具有先进先出FIFO(First In First Out)的性质 入队列&#xff1a;进行插入操作的一端称为队尾(Tail/Rear) 出…