一、简介
什么是ViewInjection?就是实现View与Region关联的方法。常见的关联方法:
//方法1 ( ViewDiscovery)
this.regionManager.RegisterViewWithRegion("RegionName", typeof(ViewClass));
//方法2 (ViewInjection )
a.MEF
view = this.container.GetExportedValue<ViewClass>();
//或view = ServiceLocator.Current.GetInstance(typeof(ViewClass));
this.regionManager.Regions["RegionName"].Add(view, "RegionName");
B. Unity
var view = _container.Resolve<ViewA>();
//或var view = _ServiceLocator.GetInstance(typeof(ViewA));
this.regionManager.Regions["RegionName"].Add(view, "RegionName");
//方法3(ViewInjection )
view = this.container.GetExportedValue<ViewClass>();
//或view = ServiceLocator.Current.GetInstance(typeof(ViewClass));
this.regionManager.AddToRegion("RegionName", view);
05-ViewInjection的注入方法:
二、举例
工程目录
下面罗列工程文件:
1、App.xaml、App.xaml.cs、Bootstrapper.cs(和系列第一个例子相同,不罗列)。
2、MainWindow.xaml
<Window x:Class="ViewInjection.Views.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:prism="http://www.codeplex.com/prism"
Title="Shell" Height="350" Width="525">
<DockPanel LastChildFill="True">
<Button DockPanel.Dock="Top" Click="Button_Click">Add View</Button>
<ContentControl prism:RegionManager.RegionName="ContentRegion" />
</DockPanel>
</Window>
3、MainWindow.xaml.cs:
using Microsoft.Practices.Unity;
using Prism.Regions;
using System.Windows;
namespace ViewInjection.Views
{
/// <summary>
/// 该类实现了ViewInjection注入,并且采用了方法2 的B.Uinty注释的形式
/// </summary>
public partial class MainWindow : Window
{
IUnityContainer _container;
IRegionManager _regionManager;
public MainWindow(IUnityContainer container, IRegionManager regionManager)
{
InitializeComponent();
_container = container;
_regionManager = regionManager;
}
private void Button_Click(object sender, RoutedEventArgs e)
{
var view = _container.Resolve<ViewA>();
IRegion region = _regionManager.Regions["ContentRegion"];
region.Add(view);
}
}
}
4、ViewA.xaml:
<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>
5、ViewA.xaml.cs(默认值,不添加任何东西)
6、输出结果(点击按钮后,输出):
7、ViewDiscovery与ViewInjection的区别?
不知道,请看官网吧,中文版么有人说它们的优缺点。