在现代C#桌面应用开发中,WPF MVVM模式是一种被广泛采用的软件架构设计模式。它不仅提高了代码的可维护性和可测试性,还实现了界面与业务逻辑的清晰分离。本文将从零开始,手把手教你如何搭建一个完整的C# MVVM架构项目,即使你是编程小白,也能轻松上手!
MVVM 是 Model-View-ViewModel 的缩写:
使用 WPF数据绑定机制,MVVM 模式可以实现 UI 自动响应数据变化,无需手动操作控件。这大大简化了代码,提升了开发效率和可测试性。
我们将创建一个显示用户姓名并能通过按钮更新的简单应用。
// UserModel.cspublic class UserModel{ public string Name { get; set; }} ViewModel 需要实现 INotifyPropertyChanged 接口,以便支持 WPF数据绑定的自动更新。
using System.ComponentModel;using System.Runtime.CompilerServices;public class MainViewModel : INotifyPropertyChanged{ private string _userName = "张三"; public string UserName { get => _userName; set { _userName = value; OnPropertyChanged(); } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); }} 为了响应按钮点击,我们需要使用 MVVM命令绑定。下面是一个简单的 RelayCommand 实现:
using System;using System.Windows.Input;public class RelayCommand : ICommand{ private readonly Action _execute; private readonly Func _canExecute; public RelayCommand(Action execute, Func canExecute = null) { _execute = execute ?? throw new ArgumentNullException(nameof(execute)); _canExecute = canExecute; } public bool CanExecute(object parameter) => _canExecute == null || _canExecute(); public void Execute(object parameter) => _execute(); public event EventHandler CanExecuteChanged { add => CommandManager.RequerySuggested += value; remove => CommandManager.RequerySuggested -= value; }} 然后在 ViewModel 中添加命令:
public class MainViewModel : INotifyPropertyChanged{ // ... 前面的 UserName 属性 ... public ICommand UpdateNameCommand { get; } public MainViewModel() { UpdateNameCommand = new RelayCommand(UpdateName); } private void UpdateName() { UserName = "李四 (已更新)"; } // ... OnPropertyChanged 方法 ...} 在 MainWindow.xaml 中绑定 ViewModel 的属性和命令:
<Window x:Class="MyApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" Title="MVVM 示例" Height="200" Width="400"> <Window.DataContext> <local:MainViewModel /> </Window.DataContext> <StackPanel Margin="20"> <TextBlock Text="当前用户名:" FontSize="16" /> <TextBlock Text="{Binding UserName}" FontSize="18" Margin="0,5" /> <Button Content="更新名称" Command="{Binding UpdateNameCommand}" FontSize="16" Padding="10" Margin="0,10" /> </StackPanel></Window> 通过以上步骤,我们成功构建了一个基于 C# MVVM架构 的 WPF 应用。核心要点包括:
INotifyPropertyChanged 支持 WPF数据绑定;ICommand 实现 MVVM命令绑定;掌握 WPF MVVM模式 是成为专业 WPF 开发者的必经之路。希望本教程能为你打下坚实基础!