Region概述
Region是Prism当中模块化的核心功能。Region可以理解为View的动态占位符,在View上进行视图占位,其主要目的是弱化模块与模块之间的耦合关系。

在一般的界面设计中,界面上的元素及内容往往是被固定,如上图。
- Header区域放置ToolBar
- Menu 区域放置ListBox
- Content 区域放置ContentControl
这使得各个区域的内容被固定下来,不能直接对该区域的元素或内容进行替换。在Prism当中,可以将页面区域定义为Region,此时可以通过修改Region设置,使得页面区域展示的内容不再固定,可以动态分配区域所展示的内容。
此时Region的功能类似于一个视图容器,可以通过设置将视图界面放到Region中,实现视图的管理

Region的使用
Region使用思路
一般在Prism项目中,将视图放在Views文件夹,Region的定义在主窗体,Region视图的注册在ViewModels文件夹。

1.视图创建

- <Grid Background="Yellow">
- <TextBlock
- Text="UserControlTempA"
- FontSize="16"
- HorizontalAlignment="Center"
- VerticalAlignment="Center"/>
- </Grid>
复制代码 2.Region定义
Region的定义可以使用XAML或代码创建定义Region:
XAML中定义:
通过prism:RegionManager.RegionName="[RegionName]"对Region进行定义,此时可以直接通过RegisterViewWithRegion将视图注册到Region当中。
- [/code][size=4]代码中定义:[/size]
- 在代码中定义需要通过x:Name为控件定义名称,再在代码中通过SetRegionName对Region进行定义
- [list]
- [*]MainWindow.xaml
- [/list][code]
复制代码- //设置Region名称,将Control2控件对应Region名称设置为"WorkRegion2"
- RegionManager.SetRegionName(Control2, "WorkRegion2");
复制代码 注:
- RegionName 一定要是唯一的
- 代码中可以直接调用Control2是由于
项目代码:


小结:
代码中定义时将Region名称定义放到了代码之中,通过XAML中的x:Name进行联结
在XAML中定义通过prism:RegionManager.RegionName="[RegionName]"对Region进行定义,一步到位;在查看视图时更方便确定哪些是Region,个人更加推荐在XAML中进行Region定义。
3.视图注册
对Region定义后,还需要将视图注册到Region中才可以使用。
Region的定义时通过regionManager来实现的,此时要将regionManager传入MainWindowViewModel,通过RegisterViewWithRegion将视图注册到Region当中。- public MainWindowViewModel(IRegionManager regionManager){<Grid Background="Yellow">
- <TextBlock
- Text="UserControlTempA"
- FontSize="16"
- HorizontalAlignment="Center"
- VerticalAlignment="Center"/>
- </Grid>//Prism框架内依赖注入的RegionManager<Grid Background="Yellow">
- <TextBlock
- Text="UserControlTempA"
- FontSize="16"
- HorizontalAlignment="Center"
- VerticalAlignment="Center"/>
- </Grid>RegionManager = regionManager;<Grid Background="Yellow">
- <TextBlock
- Text="UserControlTempA"
- FontSize="16"
- HorizontalAlignment="Center"
- VerticalAlignment="Center"/>
- </Grid>//在WorkRegion1中注册UserControlTempA视图<Grid Background="Yellow">
- <TextBlock
- Text="UserControlTempA"
- FontSize="16"
- HorizontalAlignment="Center"
- VerticalAlignment="Center"/>
- </Grid>RegionManager.RegisterViewWithRegion("WorkRegion1", typeof(UserControlTempA));<Grid Background="Yellow">
- <TextBlock
- Text="UserControlTempA"
- FontSize="16"
- HorizontalAlignment="Center"
- VerticalAlignment="Center"/>
- </Grid>//在WorkRegion2中注册UserControlTempA视图<Grid Background="Yellow">
- <TextBlock
- Text="UserControlTempA"
- FontSize="16"
- HorizontalAlignment="Center"
- VerticalAlignment="Center"/>
- </Grid>RegionManager.RegisterViewWithRegion("WorkRegion2", typeof(UserControlTempA));}
复制代码
最终效果

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |