温馨提示×

mvvm框架在c#中的应用案例

c#
小樊
171
2024-09-26 16:20:21
栏目: 编程语言

MVVM(Model-View-ViewModel)是一种软件架构设计模式,主要用于分离应用程序的用户界面(UI)和业务逻辑。在C#中,WPF(Windows Presentation Foundation)和UWP(Universal Windows Platform)是常用的实现MVVM框架的方式。以下是一个简单的WPF应用程序中应用MVVM框架的案例:

  1. 首先,创建一个新的WPF应用程序项目。

  2. 在项目中,创建一个Model类,例如Person

public class Person { public string FirstName { get; set; } public string LastName { get; set; } } 
  1. 创建一个ViewModel类,例如PersonViewModel
public class PersonViewModel : INotifyPropertyChanged { private Person _person; public PersonViewModel() { _person = new Person(); } public string FirstName { get { return _person.FirstName; } set { _person.FirstName = value; OnPropertyChanged("FirstName"); } } public string LastName { get { return _person.LastName; } set { _person.LastName = value; OnPropertyChanged("LastName"); } } public event PropertyChangedEventHandler PropertyChanged; protected virtual void OnPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } 
  1. 在MainWindow.xaml中,创建一个简单的用户界面,包括两个文本框和一个按钮:
<Window x:Class="MVVMExample.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" xmlns:local="clr-namespace:MVVMExample" mc:Ignorable="d" Title="MVVM Example" Height="200" Width="300"> <Grid> <StackPanel VerticalAlignment="Center" HorizontalAlignment="Center"> <TextBox x:Name="txtFirstName" Text="{Binding FirstName}" /> <TextBox x:Name="txtLastName" Text="{Binding LastName}" /> <Button Content="Save" Click="btnSave_Click" /> </StackPanel> </Grid> </Window> 
  1. 在MainWindow.xaml.cs中,设置数据上下文并处理按钮点击事件:
public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); DataContext = new PersonViewModel(); } private void btnSave_Click(object sender, RoutedEventArgs e) { // 在这里处理保存逻辑,例如将数据保存到数据库或文件 MessageBox.Show("保存成功!"); } } 

现在,当用户在文本框中输入名字并点击保存按钮时,ViewModel中的属性会更新,并触发PropertyChanged事件。MainWindow.xaml会自动响应这些更改并更新UI。

0