0x1 PRISM?
PRISM项目地址:https://github.com/PrismLibrary/Prismhtml
先看下简介:git
Prism is a framework for building loosely coupled, maintainable, and testable XAML applications in WPF, Windows 10 UWP, and Xamarin Forms.github
谷歌翻译:shell
Prism是一个框架,用于在WPF,Windows 10 UWP和Xamarin Forms中构建松散耦合,可维护和可测试的XAML应用程序。bootstrap
能够看出PRISM并不单单是一个MVVM框架,他提供了一系列设计模式的实现。这听上去就很Dior了。c#
0x2 Run
PRISM 再也不使用App.xaml
来为程序设置入口,而是使用 Bootstrapper来初始化程序和启动窗口。在 PRISM的项目中,须要删除App.xaml
中的StartupUri
,由于你再也不须要使用他了。设计模式
一般状况下,你的App.xaml
是这样的:app
<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> </Application.Resources> </Application>
而PRISM项目中的App.xaml
是这样的:框架
<Application x:Class="BootstrapperShell.App" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:BootstrapperShell"> <Application.Resources> </Application.Resources> </Application>
PRISM项目中,在 App.xaml.cs
中重写了OnStartup
方法,让app从Bootstrapper启动:ide
protected override void OnStartup(StartupEventArgs e) { base.OnStartup(e); var bootstrapper = new Bootstrapper(); bootstrapper.Run(); }
顺藤摸瓜,咱们看一下 Bootstrapper类
using Microsoft.Practices.Unity; using Prism.Unity; using BootstrapperShell.Views; using System.Windows; namespace BootstrapperShell { class Bootstrapper : UnityBootstrapper { protected override DependencyObject CreateShell() { return Container.Resolve<MainWindow>(); } protected override void InitializeShell() { Application.Current.MainWindow.Show(); } } }
Bootstrapper.cs
,中的CreateShell
方法来建立shell,InitializeShell
初始化shell。这里的shell是宿主应用程序,就至关因而咱们的主窗体程序,其余的view和module都将会被加载到shell中显示。
固然你也能够不用使用MainWindow
,做为shell的窗口,能够改为任何你想要的名字,但他必定是Window类型,你还能够将他放在任何一个位置,为了未来适配MVVM思想,咱们将他放在Views目录下面,之后咱们全部的View都将放到这个目录下面。
那么,咱们在初识WPF的时候,认识的App.g.cs
呢?他里面不是有Main方法吗?咱们在一样的位置找到他:
using BootstrapperShell; using System.Windows.Shell; namespace BootstrapperShell { /// <summary> /// App /// </summary> public partial class App : System.Windows.Application { /// <summary> /// Application Entry Point. /// </summary> [System.STAThreadAttribute()] [System.Diagnostics.DebuggerNonUserCodeAttribute()] [System.CodeDom.Compiler.GeneratedCodeAttribute("PresentationBuildTasks", "4.0.0.0")] public static void Main() { BootstrapperShell.App app = new BootstrapperShell.App(); app.Run(); } } }
蛤蛤,他叛变了,App.g.cs
看上去更像是一个在编译的时候才会生成的中间文件,根据App.xaml.cs
中的OnStartup
方法来从新生成了Main方法。
[7.1update]Prism.UnityUnityBootstrapper
被标记为 deprecated,而且建议使用 PrismApplication
做为应用的基类,而且在7.1中Bootstrapper
类已经再也不使用,入口代码整合到app.xaml及app.xaml.cs中去了,但这一节不影响咱们来了解wpf及prism,在接下来的例子中我会将实例代码更新到7.1。