C# WPF通过反射及Ioc容器加载并显示其它项目界面(精品)

[删除(380066935@qq.com或微信通知)]

更好的阅读体验请查看原文:https://mp.weixin.qq.com/s/_Hw15CqJ7bX4OUsZHy_2jQ

概述

    这节主要通过发射+Caliburn.Micro自带的ioc容器实现加载并显示其它项目中的界面.实现效果如下: 

具体实现

   -. ①首先在引导程序页面通过发射加载类库,并将视图注入ioc容器,这里为了实现解耦合注入了ICommonBasePage接口类型:

 private void ExternalLoad()        {            //container = new SimpleContainer();            //container.Instance(container);
var asmPath = Assembly.GetAssembly(typeof(HelloBootstrapper)).Location; var path = Directory.GetParent(asmPath).FullName; string filePath = Path.Combine(path, "PluginTest.dll");
//var assembly = Assembly.GetAssembly(typeof(PageBase)); //container.AllTypesOf<ShellViewModel>(assembly); var assembly = Assembly.LoadFile(filePath); assembly.GetTypes() .Where(type => type.IsClass) .Where(type => type.Name.EndsWith("ViewModel")) .ToList() .ForEach(viewModelType => container.RegisterPerRequest( typeof(ICommonBasePage), viewModelType.ToString(), viewModelType));
//container // .Singleton<IWindowManager, WindowManager>() // .Singleton<IEventAggregator, EventAggregator>() // .PerRequest<MainWindowViewModel>(); }

接口定义在单独的类库中:

   public interface ICommonBasePage    {        void ShowNewWindow();    }

加入程序集到IEnumerable<Assembly>

protected override IEnumerable<Assembly> SelectAssemblies()        {            string filePath = Path.Combine(Directory.GetCurrentDirectory(), "PluginTest.dll");
var assembly = Assembly.LoadFile(filePath); return new[] { Assembly.GetExecutingAssembly(), assembly }; }


-.②PluginTest是要加载显示的项目:

PluginTestViewModel.cs源码如下:

using CommonShareBase;using System.ComponentModel.Composition;using System.Windows;
namespace PluginTest{ //[PluggablePart(name: "PluginTestViewModel", desciption: "This is PluginTestViewModel content pluggable part.", displayNameResourceKey: "PluginTestViewModel")] //[Export("PluginTestViewModel", typeof(IPluggablePart))] //[PartCreationPolicy(CreationPolicy.Shared)] ///也可以这样 [Export(typeof(ICommonBasePage))] public class PluginTestViewModel : ICommonBasePage { //public void PreparePart(IPluggablePartContext pluggablePartContext) //{ // //throw new NotImplementedException(); //}
public void ShowNewWindow() { MessageBox.Show("dotnet讲堂"); } }}

PluginTestView.xaml代码如下:

<UserControl x:Class="PluginTest.PluginTestView"             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:PluginTest"             mc:Ignorable="d"              d:DesignHeight="450" d:DesignWidth="800">    <Grid ShowGridLines="True">        <Grid.RowDefinitions>            <RowDefinition Height="*" />            <RowDefinition Height="*" />
</Grid.RowDefinitions> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Button Name="ShowNewWindow" Content="ShowNewWindow" Grid.Row="0" Grid.Column="0" FontSize="35" Background="LightBlue"/> </Grid></UserControl>


-. ③在调用的地方先定义ICommonBasePage 类型的VM

 public ICommonBasePage PluginTestViewModel { get; set; }

按钮事件里面从ioc获取视图并给界面赋值:

  public void IocTest4()        {            //通过接口实现解耦合            var shellVM = IoC.Get<ICommonBasePage>();            //shellVM.ShowNewWindow();
PluginTestViewModel = shellVM; ActivateItemAsync(PluginTestViewModel); }

源码下载

链接:https://pan.baidu.com/s/1wtNduWVUiFV46WwWE4hrEw

提取码:6666