Prism Sample 5 View Injection
这里稍微复杂了点,定义视图A的过程是一样的:
<UserControl x:Class="ViewInjection.Views.ViewA" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:local="clr-namespace:ViewInjection.Views" mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300"> <Grid> <TextBlock Text="View A" FontSize="38" /> </Grid> </UserControl>
但是与前面不同的是,需要点击按钮之后才能显示,这个在MainWindow的后台文件中体现:
public partial class MainWindow : Window { IContainerExtension _container; IRegionManager _regionManager; public MainWindow(IContainerExtension container, IRegionManager regionManager) { InitializeComponent(); _container = container; _regionManager = regionManager; } private void Button_Click(object sender, RoutedEventArgs e) { var view = _container.Resolve<ViewA>(); var region = _regionManager.Regions["ContentRegion"]; region.Add(view); } }
这里所称的注入,首先是在构造函数中注入了容器和区域管理器,然后在Button的后台中,先生成View的实例,再找到Region,最后向Region中Add(View)。
由些看来,View Injection的方法更透明,也就是说这个过程更可控,在下面的情况下,建议使用Injection。
不知道为什么在引用之后没法插入文字了。
有道翻译:
例如,作为应用程序逻辑的结果,对何时创建和显示视图,或何时需要从区域中删除视图进行显式或编程控制。
将相同视图的多个实例显示到一个区域中,每个视图实例绑定到不同的数据。
控制添加哪个区域实例的视图(例如,如果您想将客户详细信息视图添加到特定的客户详细信息区域)。请注意,
此场景需要本主题后面描述的范围区域。
- Explicit or programmatic control over when a view is created and displayed, or when you need to remove a view from a region, for example, as a result of application logic.
- To display multiple instances of the same views into a region, where each view instance is bound to different data.
- To control which instance of a region a view is added (for example, if you want to add customer detail view to a specific customer detail region). Note that
this scenario requires scoped regions described later in this topic.