MVVM
- 1. 简介
- 2. 示例
1. 简介
2. 示例
示例下载地址:https://download.csdn.net/download/qq_43572400/88925141
-
创建C# WPF应用(.NET Framework)工程,WpfApp1
-
添加程序集 GalaSoft.MvvmLight
-
创建ViewModel文件夹,并创建MainWindowViewModel.cs、ViewModelLocator.cs文件
MainWindowViewModel.cs为视图模型类,用于管理应用程序的主要逻辑
public class MainWindowViewModel : ViewModelBase
{public MainWindowViewModel(){Title = "主界面";}private string _Title;public string Title{get { return _Title; }set { Set(ref _Title, value); }}
}
ViewModelLocator.cs用于提供 MainWindowViewModel 的实例
public class ViewModelLocator
{public ViewModelLocator(){ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);SimpleIoc.Default.Register<MainWindowViewModel>();}public MainWindowViewModel MainWindow{get{return ServiceLocator.Current.GetInstance<MainWindowViewModel>();}}
}
注意 |
---|
① 定义的参数名必须与xml中path定义名一致 |
② return ServiceLocator.Current.GetInstance();指页面关闭后,页面参数保存在内存中,程序不关闭则参数一直存在 |
③ return New MainWindowViewModel(); 指每次打开一个新的页面 |
- 在App.xaml文件中,添加一个资源字典(ResourceDictionary)并定义一个名为"Locator"的静态资源:
<Application x:Class="WpfApp1.App"xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"xmlns:local="clr-namespace:WpfApp1"StartupUri="MainWindow.xaml"><Application.Resources><ResourceDictionary><local:ViewModelLocator x:Key="Locator" xmlns:local="clr-namespace:WpfApp1.ViewModel"/></ResourceDictionary></Application.Resources>
</Application>
- 在XAML中设置"MainViewModel"作为主窗口的DataContext,使用资源字典(ResourceDictionary)和ViewModelLocator来实现这一点
MainWindow.xaml
<Window x:Class="WpfApp1.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:WpfApp1"mc:Ignorable="d"Title="{Binding Title}" Height="450" Width="800"><Window.DataContext><Binding Path="MainWindow" Source="{StaticResource Locator}"></Binding></Window.DataContext><Grid></Grid>
</Window>
注意:Path定义的名称必须跟ViewModelLocator中声明的函数名一致,否则定义的*ViewModel.cs类不生效。
- 运行后MainWindowViewModel 设置的标题Title生效