MVVM(Model-View-ViewModel)是一种软件架构设计模式,主要用于分离应用程序的用户界面(UI)和业务逻辑。在C#中,WPF(Windows Presentation Foundation)和UWP(Universal Windows Platform)是常用的实现MVVM框架的方式。以下是一个简单的WPF应用程序中应用MVVM框架的案例:
首先,创建一个新的WPF应用程序项目。
在项目中,创建一个Model类,例如Person
:
public class Person
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
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));
}
}
<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>
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。