從PRISM開始學WPF(二)Prism?
目錄:
從PRISM開始學WPF(一)WPF?
從PRISM開始學WPF(二)Prism?
從PRISM開始學WPF(三)Prism-Region?
從PRISM開始學WPF(四)Prism-Module?
從PRISM開始學WPF(五)MVVM(一)ViewModel?
從PRISM開始學WPF(六)MVVM(二)Command?
從PRISM開始學WPF(七)MVVM(三)事件聚合器EventAggregator?
0x1 PRISM?
PRISM項目地址:https://github.com/PrismLibrary/Prism
先看下簡介:
Prism is a framework for building loosely coupled, maintainable, and testable XAML applications in WPF, Windows 10 UWP, and Xamarin Forms.
谷歌翻譯:
Prism是一個框架,用於在WPF,Windows 10 UWP和Xamarin Forms中構建松散耦合,可維護和可測試的XAML應用程序。
可以看出PRISM並不僅僅是一個MVVM框架,他提供了一系列設計模式的實現。這聽上去就很Dior了。
0x2 Run
PRISM 不再使用App.xaml
App.xaml
中的StartupUri
,因為你不再需要使用他了。
通常情況下,你的App.xaml
是這樣的:
<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啟動:
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var bootstrapper = new Bootstrapper();
bootstrapper.Run();
}
Bootstrapper.cs
,中的CreateShell
方法來創建shell,InitializeShell
初始化shell。這裏的shell是宿主應用程序,就相當於是我們的主窗體程序,其他的view和module都將會被加載到shell中顯示。下面是Bootstrapper.cs
類內容:
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();
}
}
}
當然你也可以不用使用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方法。
從PRISM開始學WPF(二)Prism?