您的位置:首页 > 其它

一步步实现 Prism + MEF(一)--- 搭建框架

2017-12-18 10:10 471 查看
第一步:构建一个名为Bootstrapper的类作为引导程序。

class Bootstrapper : MefBootstrapper
{
}


第二步:在MainWindow窗体中添加一个CoontentControl控件作为模块的容器,并在后台代码中添加[Export]属性以便MEF可以注入。

窗体代码:

<ContentControl prism:RegionManager.RegionName="MainRegion" />


后台代码:

using System.ComponentModel.Composition;

[Export(typeof(MainWindow))]
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}


第三步:在Bootstrapper类中重写CreateShell方法以便返回一个Shell(MainWindow)实例。

protected override DependencyObject CreateShell()
{
return Container.GetExportedValue<MainWindow>();
}


第四步:在Bootstrapper类中重写InitializeShell方法以便启动Shell。

protected override void InitializeShell()
{
Application.Current.MainWindow.Show();
}


第五步:在Bootstrapper类中重写ConfigureAggregateCatalog方法,将所有带有[Export]属性的类所在的程序集目录添加进去。

protected override void ConfigureAggregateCatalog()
{
base.ConfigureAggregateCatalog();
this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(Bootstrapper).Assembly));
this.AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(ModuleAModule).Assembly));
}


第六步:创建一个类库项目MoudleA,添加类ModuleAModule并实现IModule接口,为该类添加[ModuleExport]属性以便让该类成为Prism模块初始化类。

[ModuleExport(typeof(ModuleAModule))]
public class ModuleAModule : IModule
{
IRegionManager _regionManager;

// 当Prism加载该模块时,它将通过MEF实例化该类,MEF将注入一个Region Manager实例
[ImportingConstructor]
public ModuleAModule(IRegionManager regionManager)
{
_regionManager = regionManager;
}

// 该方法将为模块启动提供一个代码入口点
// 我们将把MEF容器里的ViewA注入到MainWindow界面定义的MainRegion中
public void Initialize()
{
_regionManager.RegisterViewWithRegion("MainRegion", typeof(ViewA));
}
}


第七步:在ModuleA项目中添加ViewA用户控件,并在后台代码中添加[Export]属性,以便MEF在需要的时候能注入它。

窗口代码:

<Grid>
<!--  绑定ViewModel中的Title属性 -->
<TextBlock Text="{Binding Title}" Foreground="Green" HorizontalAlignment="Center" VerticalAlignment="Center" FontFamily="Calibri" FontSize="24" FontWeight="Bold"></TextBlock>
</Grid>


后台代码:

[Export(typeof(ViewA))]
public partial class ViewA : UserControl
{
public ViewA()
{
InitializeComponent();
}
}


 第八步:在ModuleA项目中添加ViewAViewModel类

[Export(typeof(ViewAViewModel))]
public class ViewAViewModel : BindableBase
{
private string _title = "Hello World";
public string Title
{
get { return _title; }
set { SetProperty(ref _title, value); }
}
}


完成上述步骤之后就可以在App.xaml.cs中直接运行Bootstrapper引导程序。

protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);

Bootstrapper bs = new Bootstrapper();
bs.Run();
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: