我们正在构建WPF Prism应用程序。我们有不同的开发人员从事不同的模块项目,并且将多个模块注入(inject)到主Application Shell中。主应用程序也是一个单独的项目。我们还希望能够在不同的应用程序中使用这些模块。我们不想在每个应用程序中都使用相同的名称来命名区域。

例如,假设我们有一个要在两个不同应用程序中使用的模块。在一个应用程序中,其开发人员可以将模块的区域命名为“DetailsRegion”,在另一个应用程序中,其开发人员可以将其命名为“ResultsRegion”。

我可以找到的每个示例都通过在模块的类定义中对区域名称进行硬编码来将 View 注册到区域:

myRegionManager.RegisterViewWithRegion("RegionNameHere", GetType(ModuleViewType))

我要执行的操作是将Region名称放入主应用程序的app.config文件中,并将此名称传递给模块。像这样的东西:

在主Shell应用程序的app.config中:
<Modules>
   <SearchModule>
       <add key="RegionName" value="SearchRegion" />
    </SearchModule>
</Modules>

并在模块的类文件中:
Dim settings As NameValueCollection = CType(ConfigurationManager.GetSection("Modules/SearchModule"), NameValueCollection)
Dim regionName as string = settings("RegionName")
myRegionManager.RegisterViewWithRegion(regionName, GetType(SearchModuleType)

从某种意义上讲,这是将模块与 shell 以及彼此完全分离的最后一步。

这在模块的 View 中可以完美地工作。但是我无法在模块的类定义文件中执行此操作,因为ConfigurationManager在该级别不可用。

我可以通过将区域名称放在模块的app.config的ApplicatonSettings部分中来实现。但这达不到将模块存储在一个位置以供多个应用程序加载的目的。它确实需要在主应用程序的app.config中。

有没有一种方法可以在不使用代码硬编码区域名称的情况下向区域注册模块的 View ?我们非常努力地不对任何内容进行硬编码。这里真的有必要吗?

最佳答案

正如Meleak在其评论中已经提到的:使用静态类

namespace Infrastructure
{
    public static class RegionNames
    {
        public const string MainRegion = "MainRegion";
    }
}

在您的xaml代码中,您可以按以下方式使用区域名称:
<UserControl
    xmlns:Inf="clr-namespace:Infrastructure;assembly=Infrastructure"
    xmlns:Regions="clr-namespace:Microsoft.Practices.Prism.Regions;assembly=Microsoft.Practices.Prism">
    <ContentControl Regions:RegionManager.RegionName="{x:Static Inf:RegionNames.MainRegion}"/>
</UserControl>

关于wpf - 棱镜/MEF : How to RegisterViewWithRegion Without Hard-Coding the Region Name,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7408235/

10-09 08:09