当前位置: 首页> 汽车> 维修 > WPF学习(7) --MVVM模式

WPF学习(7) --MVVM模式

时间:2025/7/10 12:33:55来源:https://blog.csdn.net/Fourglsl/article/details/140445295 浏览次数: 0次

1. MVVM模式概述

MVVM模式由三个主要部分组成:

  • Model(模型):包含应用程序的业务逻辑和数据。通常是数据对象和数据访问层。
  • View(视图):用户界面部分,展示数据并与用户进行交互。通常是XAML文件。
  • ViewModel(视图模型):视图与模型之间的桥梁。它从Model中获取数据并准备好让View使用,同时处理用户的交互。

2. MVVM模式在WPF中的实现

2.1 Model   Model: Person.cs

Model通常是数据实体类和数据访问层,可以从数据库或服务中获取数据。下面是一个简单的Model示例:

public class Person
{public string Name { get; set; }public int Age { get; set; }
}

2.2 ViewModel   ViewModel: PersonViewModel.cs

ViewModel负责从Model获取数据并准备好供View使用。ViewModel通常实现INotifyPropertyChanged接口,以便通知View属性值的变化。

using System.ComponentModel;public class PersonViewModel : INotifyPropertyChanged
{private Person _person;public PersonViewModel(){_person = new Person { Name = "John Doe", Age = 30 };}public string Name{get { return _person.Name; }set{if (_person.Name != value){_person.Name = value;OnPropertyChanged("Name");}}}public int Age{get { return _person.Age; }set{if (_person.Age != value){_person.Age = value;OnPropertyChanged("Age");}}}public event PropertyChangedEventHandler PropertyChanged;protected void OnPropertyChanged(string propertyName){PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));}
}

2.3 View   View: MainWindow.xaml

View是用户界面部分,使用XAML定义界面布局和绑定。下面是一个简单的View示例:

<Window x:Class="MVVMExample.MainWindow"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"Title="MainWindow" Height="200" Width="400"><Grid><StackPanel><TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}" /><TextBox Text="{Binding Age, UpdateSourceTrigger=PropertyChanged}" /><TextBlock Text="{Binding Name}" /><TextBlock Text="{Binding Age}" /></StackPanel></Grid>
</Window>

2.4 Code-Behind: MainWindow.xaml.cs

要使绑定工作,需要在窗口的代码后面设置DataContext:

public partial class MainWindow : Window
{public MainWindow(){InitializeComponent();DataContext = new PersonViewModel();}
}
关键字:WPF学习(7) --MVVM模式

版权声明:

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

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

责任编辑: