关于WPF:PrismWPF-Prism框架使用上

30次阅读

共计 2374 个字符,预计需要花费 6 分钟才能阅读完成。

本文参考 Prism 官网示例

创立 Prism 我的项目

  1. 将 App.xaml 中的 WPF 规范 Application 替换为 PrismApplication,移除 StartupUri 属性;
  2. 将 App.xaml.cs 中的基类改为 PrismApplication;
  3. 必须实现 PrismApplication 中的两个形象办法:RegisterTypes、CreateShell;
  4. RegisterTypes 用来注册类型;
  5. CreateShell 用来创立程序主窗口。

Region 应用

  1. 在 view xaml 文件中应用 prism:RegionManager.RegionName="SomeRegion" 标记 region;
  2. 创立自定义 RegionAdapter 类,继承自 RegionAdapterBase<T>,override Adapt 和 CreateRegion 办法;
  3. 在 App.xaml.cs 中通过 override ConfigureRegionAdapterMappings 办法注册自定义 RegionAdapter,示例如下:
protected override void ConfigureRegionAdapterMappings(RegionAdapterMappings regionAdapterMappings)
{base.ConfigureRegionAdapterMappings(regionAdapterMappings);
    regionAdapterMappings.RegisterMapping(typeof(StackPanel), Container.Resolve<StackPanelRegionAdapter>());
}

View 注入 Region

有两种办法,第一种称为 View Discovery,该办法实用于当 region 加载时就把视图注入到 region 场景;另外一种办法称为 View Injection,该办法实用于当激发某一事件后 view 注入到 region 场景。

View Discovery

通过如下办法实现:

regionManager.RegisterViewWithRegion("ContentRegion", typeof(ViewA));
View Injection

通过如下办法实现,并可通过 IRegion 的 Activate 与 Deactivate 接口实现 view 的使能:

private void Button_Click(object sender, RoutedEventArgs e)
{var view = _container.Resolve<ViewA>();
    IRegion region = _regionManager.Regions["ContentRegion"];
    region.Add(view);
}

private void Button_Click(object sender, RoutedEventArgs e)
{
    //activate view a
    _region.Activate(_viewA);
}

private void Button_Click_1(object sender, RoutedEventArgs e)
{
    //deactivate view a
    _region.Deactivate(_viewA);
}

增加视图模块

  1. 增加我的项目,在我的项目中增加继承自 IModule 的类,实现 OnInitialized 与 RegisterTypes 办法。个别在 OnInitialized 中增加 View Discovery 代码以将该模块的相干 View 注入到 Region 中;
  2. 在程序中增加模块。增加模块的形式很多,本文仅介绍应用代码的形式增加,办法如下:
// App.xaml.cs
protected override void ConfigureModuleCatalog(IModuleCatalog moduleCatalog)
{moduleCatalog.AddModule<ModuleA.ModuleAModule>();
}

匹配 ViewModels

如果不批改命名规定,在 xaml 中为窗口 / 控件增加如下属性将主动匹配 viewmodel:

prism:ViewModelLocator.AutoWireViewModel="True"

能够通过如下办法批改默认的 viewmodel 匹配规定,仍需在 xaml 中配置 AutoWireViewModel:

// App.xaml.cs
protected override void ConfigureViewModelLocator()
{base.ConfigureViewModelLocator();

    ViewModelLocationProvider.SetDefaultViewTypeToViewModelTypeResolver((viewType) =>
    {
        var viewName = viewType.FullName;
        var viewAssemblyName = viewType.GetTypeInfo().Assembly.FullName;
        var viewModelName = $"{viewName}ViewModel, {viewAssemblyName}";
        return Type.GetType(viewModelName);
    });
}

若不想批改匹配规定,且 viewmodel 名称不匹配默认规定,可通过如下形式匹配,仍需在 xaml 中配置 AutoWireViewModel:

protected override void ConfigureViewModelLocator()
{base.ConfigureViewModelLocator();
    
    ViewModelLocationProvider.Register<MainWindow, CustomViewModel>();}

正文完
 0