MVVM(Model-View-ViewModel)是一种用于构建用户界面的设计模式,它将视图(View)和业务逻辑(Model)分离,通过视图模型(ViewModel)进行交互。下面将详细介绍如何在 C# 中自己实现一个简单的 MVVM 模式示例。
1. 创建项目
首先,打开 Visual Studio,创建一个新的 WPF 应用程序项目。
2. 定义 Model
Model 代表应用程序的数据和业务逻辑。创建一个简单的 Person
类作为示例:
收起
csharp
// Model 类
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
3. 实现 INotifyPropertyChanged 接口
为了实现数据绑定和属性更改通知,需要实现 INotifyPropertyChanged
接口。创建一个 ViewModelBase
基类,所有的视图模型都可以继承自该类:
收起
csharp
using System.ComponentModel;
using System.Runtime.CompilerServices;
// 视图模型基类,实现 INotifyPropertyChanged 接口
public class ViewModelBase : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected bool SetProperty<T>(ref T storage, T value, [CallerMemberName] string propertyName = null)
{
if (Equals(storage, value))
{
return false;
}
storage = value;
OnPropertyChanged(propertyName);
return true;
}
}
4. 创建 ViewModel
ViewModel 负责处理视图的逻辑和数据。创建一个 PersonViewModel
类,继承自 ViewModelBase
:
收起
csharp
// 视图模型类
public class PersonViewModel : ViewModelBase
{
private Person _person;
public PersonViewModel()
{
_person = new Person { Name = "John", Age = 30 };
}
public string Name
{
get { return _person.Name; }
set
{
if (_person.Name != value)
{
_person.Name = value;
OnPropertyChanged();
}
}
}
public int Age
{
get { return _person.Age; }
set
{
if (_person.Age != value)
{
_person.Age = value;
OnPropertyChanged();
}
}
}
}
5. 创建 View
在 XAML 中创建视图,并将其绑定到 ViewModel。打开 MainWindow.xaml
文件,添加以下代码:
收起
xml
<Window x:Class="MVVMExample.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MVVM Example" Height="350" Width="525">
<Grid>
<StackPanel Orientation="Vertical" Margin="20">
<TextBlock Text="Name:" Margin="0,0,0,5"/>
<TextBox Text="{Binding Name, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="0,0,0,20"/>
<TextBlock Text="Age:" Margin="0,0,0,5"/>
<TextBox Text="{Binding Age, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}" Margin="0,0,0,20"/>
<TextBlock Text="You entered:" Margin="0,0,0,5"/>
<TextBlock Text="{Binding Name}" Margin="0,0,0,5"/>
<TextBlock Text="{Binding Age}" />
</StackPanel>
</Grid>
</Window>
6. 关联 View 和 ViewModel
在 MainWindow.xaml.cs
文件中,将 ViewModel 设置为窗口的 DataContext
:
收起
csharp
using System.Windows;
namespace MVVMExample
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new PersonViewModel();
}
}
}
7. 运行项目
按下 F5 运行项目,你将看到一个简单的界面,其中包含两个文本框用于输入姓名和年龄,以及两个文本块用于显示输入的值。当你在文本框中输入内容时,文本块会实时更新显示。
总结
通过以上步骤,你已经实现了一个简单的 MVVM 模式。关键要点包括:
- Model:负责存储数据和业务逻辑。
- ViewModel:负责处理视图的逻辑和数据,并实现
INotifyPropertyChanged
接口以实现属性更改通知。 - View:通过数据绑定与 ViewModel 进行交互。
这种分离使得代码更易于维护和测试,同时提高了代码的可重用性。