12、ViewModelLocator-Prism的MVVM,可以关联View 和ViewModel
1、将App.xaml中的StartupUri="MainWindow.xaml"删除。
2、使用NuGet安装Prism.Wpf、Prism.Core、Prism.Unity。
3、添加类“Bootstrapper”,编辑如下:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 using System.Windows; 7 using Microsoft.Practices.Unity; 8 using Prism.Mvvm; 9 using Prism.Unity; 10 using ViewModelCustom.ViewModel; 11 using ViewModelCustom.Views; 12 13 namespace ViewModelCustom 14 { 15 class BootStarpper:UnityBootstrapper 16 { 17 protected override DependencyObject CreateShell() 18 { 19 return Container.Resolve<MainWindow>(); 20 } 21 22 protected override void InitializeShell() 23 { 24 Application.Current.MainWindow.Show(); 25 } 26 27 protected override void ConfigureViewModelLocator() 28 { 29 base.ConfigureViewModelLocator(); 30 31 ViewModelLocationProvider.Register<MainWindow,CustomViewModel>(); 32 } 33 } 34 }
4、创建文件夹Views,将MainWindow.xaml移动到此文件夹中。创建文件夹ViewModels,新建类MainWindowViewModel.cs。注意:VM类的名称一定是V+“ViewModel”,例如MainWindow+“ViewModel”。
1 <Window x:Class="ViewModelLocator.Views.MainWindow" 2 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 3 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 4 xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 5 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 6 xmlns:local="clr-namespace:ViewModelLocator" 7 xmlns:prism="http://prismlibrary.com/" 8 prism:ViewModelLocator.AutoWireViewModel="True" 9 mc:Ignorable="d" 10 Title="{Binding Title}" Height="350" Width="525"> 11 <Grid> 12 13 </Grid> 14 </Window>
1 using Prism.Mvvm;
2
3 namespace ViewModelLocator.ViewModels
4 {
5 class MainWindowViewModel:BindableBase
6 {
7 private string _title = "Prism Unity Application";
8
9 public string Title
10 {
11 get { return _title; }
12 set { SetProperty(ref _title, value); }
13 }
14 }
15 }
5、修改App.xaml
1 using System.Collections.Generic; 2 using System.Configuration; 3 using System.Data; 4 using System.Linq; 5 using System.Threading.Tasks; 6 using System.Windows; 7 8 namespace BootstrapperShell 9 { 10 /// <summary> 11 /// App.xaml 的交互逻辑 12 /// </summary> 13 public partial class App : Application 14 { 15 protected override void OnStartup(StartupEventArgs e) 16 { 17 base.OnStartup(e); 18 19 var bootstrapper = new Bootstrapper(); 20 bootstrapper.Run(); 21 } 22 } 23 }
6、最终结果:
转载于:https://www.cnblogs.com/bjxingch/articles/9562542.html