我已经在我的应用程序中做到了这一点。这是我想出的代码:
string regionName = "MyRegionName";
ContentPresenter RegionContentControl = new ContentPresenter { Focusable = false };
// This creates the region
Microsoft.Practices.Prism.Regions.RegionManager.SetRegionName(RegionContentControl, regionName);
// This adds the region to your region manager.
Microsoft.Practices.Prism.Regions.RegionManager.SetRegionManager(RegionContentControl, RegionManager);
// Get the region back
IRegion newRegion = RegionManager.Regions.FirstOrDefault(x => x.Name == regionName);
我从 Unity 获得 RegionManger。
更新:
Mark 指出,ContentPresenter 是不允许开箱即用的。这是在以下位置添加该功能的适配器:
public class ContentPresenterRegionAdapter : RegionAdapterBase<ContentPresenter>
{
public ContentPresenterRegionAdapter(IRegionBehaviorFactory behaviorFactory)
: base(behaviorFactory)
{
}
protected override void Adapt(IRegion region, ContentPresenter regionTarget)
{
region.Views.CollectionChanged += (s, e) =>
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (FrameworkElement element in e.NewItems)
{
regionTarget.Content = element;
}
}
else if (e.Action == NotifyCollectionChangedAction.Remove)
{
foreach (FrameworkElement currentElement in e.OldItems)
regionTarget.Content = null;
}
};
}
protected override IRegion CreateRegion()
{
return new AllActiveRegion();
}
}
要注册此映射,您需要将其添加到引导程序中:
protected override RegionAdapterMappings ConfigureRegionAdapterMappings()
{
RegionAdapterMappings mappings = base.ConfigureRegionAdapterMappings();
mappings.RegisterMapping(typeof(ContentPresenter),
Container.Resolve<ContentPresenterRegionAdapter>());
return mappings;
}