首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

手把手建立第一個 Prism WPF 應用:Shell、模組、配置檔載入與 Region 視圖注入

     編輯:關於.NET

前置準備

  • 下載 CAL (Composite Application Library) DLL
  • Visual Studio 2008+

建立 Shell 專案

  1. 新建 WPF Application,參考 CAL 組件
  2. 將主視窗重命名為 Shell
  3. 新增 Bootstrapper 繼承 UnityBootstrapper,重寫 CreateShell、GetModuleEnumerator
  4. 修改 App.xaml 移除 StartupUri,在 App 建構子呼叫 new Bootstrapper().Run()
internal class Bootstrapper : UnityBootstrapper {
    protected override DependencyObject CreateShell() {
        var shell = new Shell(); shell.Show(); return shell;
    }
    protected override IModuleEnumerator GetModuleEnumerator() {
        return new StaticModuleEnumerator(); // 暫時用靜態,稍後改配置檔
    }
}

建立 HelloWorld 模組

  1. 方案新增 Class Library 專案 HelloWorldModule,參考 CAL
  2. 實作 IModule,Initialize 顯示 MessageBox
public class HelloWorldModule : IModule {
    public void Initialize() { MessageBox.Show("this is hello module"); }
}

採用配置檔動態載入模組

  1. Shell 專案加入 App.config,設定 <modules> 區段
  2. Bootstrapper 改回傳 ConfigurationModuleEnumerator
  3. 模組專案 Post-build event 加入 xcopy 複製輸出至 Shell bin\Debug
<configSections>
  <section name="modules" type="Microsoft.Practices.Composite.Modularity.ModulesConfigurationSection, Microsoft.Practices.Composite"/>
</configSections>
<modules>
  <module assemblyFile="HelloWorldModule.dll" moduleType="HelloWorldModule.HelloWorldModule" moduleName="HelloWorldModule"/>
</modules>
protected override IModuleEnumerator GetModuleEnumerator() {
    var configStore = new ConfigurationStore();
    return new ConfigurationModuleEnumerator(configStore);
}

將視圖注入 Shell Region

  1. Shell.xaml 加入 ItemsControl 並設定 cal:RegionManager.RegionName="MainRegion"
  2. 模組專案加入 HelloWorldView (UserControl)
  3. 模組建構子注入 IRegionManager,Initialize 中取得 Region、Add/Activate 視圖
public class HelloWorldModule : IModule {
    private readonly IRegionManager _regionManager;
    public HelloWorldModule(IRegionManager regionManager) { _regionManager = regionManager; }
    public void Initialize() {
        var mainRegion = _regionManager.Regions["MainRegion"];
        var view = new HelloWorldView();
        mainRegion.Add(view);
        mainRegion.Activate(view);
    }
}

完成!啟動即可見到視圖顯示於 Shell 內。此範例為簡化示範,實際專案建議遵循 MVP/MVC 模式組織模組內部。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved