11、ViewModelLocator-Prism的MVVM一血
1、将App.xaml中的StartupUri="MainWindow.xaml"删除。
2、使用NuGet安装Prism.Wpf、Prism.Core、Prism.Unity。
3、添加类“Bootstrapper”,编辑如下:
1 using Microsoft.Practices.Unity;
2 using Prism.Unity;
3 using System.Windows;
4 using BootstrapperShell.Views;
5
6 namespace BootstrapperShell
7 {
8 public class Bootstrapper : UnityBootstrapper
9 {
10 protected override DependencyObject CreateShell()
11 {
12 return Container.Resolve<MainWindow>();
13 }
14
15 protected override void InitializeShell()
16 {
17 Application.Current.MainWindow.Show();
18 }
19 }
20 }
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、最终结果:
风中代表自由、寻觅代表不断前进~!