MVVM(Model-View-ViewModel)是一种用于构建用户界面的软件设计模式,它将应用程序分为三个核心组件:模型(Model)、视图(View)和视图模型(ViewModel)。MVVM的目标是实现界面逻辑与用户界面的分离,提高代码的可维护性和可测试性。
MVVM带来了以下优点:
public class PersonModel
{
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class PersonViewModel : INotifyPropertyChanged
{
private PersonModel _person;
public PersonViewModel()
{
_person = new PersonModel();
}
public string FirstName
{
get { return _person.FirstName; }
set
{
if (_person.FirstName != value)
{
_person.FirstName = value;
OnPropertyChanged(nameof(FirstName));
}
}
}
public string LastName
{
get { return _person.LastName; }
set
{
if (_person.LastName != value)
{
_person.LastName = value;
OnPropertyChanged(nameof(LastName));
}
}
}
// INotifyPropertyChanged实现省略...
private void OnPropertyChanged(string propertyName)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
public event PropertyChangedEventHandler PropertyChanged;
}
<Window x:Class="MVVMSample.MainWindow"
xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="https://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:MVVMSample"
mc:Ignorable="d"
Title="MainWindow" Height="200" Width="300">
<Grid>
<StackPanel Margin="10">
<TextBox Text="{Binding FirstName}" Margin="0 0 0 5"/>
<TextBox Text="{Binding LastName}" Margin="0 0 0 5"/>
<Button Content="Submit" Command="{Binding SubmitCommand}"/>
</StackPanel>
</Grid>
</Window>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
// 关联视图模型
DataContext = new PersonViewModel();
}
}
public class PersonViewModel : INotifyPropertyChanged
{
// 其他代码省略...
public ICommand SubmitCommand => new RelayCommand(Submit);
private void Submit()
{
MessageBox.Show($"Submitted: {FirstName} {LastName}");
}
}
MVVM设计模式通过将应用程序分为模型、视图和视图模型,实现了解耦和分离关注点的目标。上述实例演示了如何在WPF中应用MVVM,通过数据绑定和命令使得界面逻辑更清晰、易于测试和维护。