欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 建筑 > C# WPF入门学习主线篇(三十二)—— 创建Model、View和ViewModel

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

2025/11/5 23:42:39 来源:https://blog.csdn.net/weixin_56595425/article/details/139654516  浏览:    关键词:C# WPF入门学习主线篇(三十二)—— 创建Model、View和ViewModel

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开发的水平。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词