C# 使用MEF动态加载不同的userControl,并实现不同userControl之间通信
1、 首先在项目的引用中添加:System.ComponentModel.Composition和bbv.Common.EventBroker
其中bbv.Common.EventBroker引用的dll库在http://sourceforge.net/projects/bbvcommon/中可以下载,如果获取不到,可以留言与我,我提供给大家。
如图所示:
2、具体代码实现
1)、主窗体代码:
public partial class frmMain : Form { private void initMEF() { AggregateCatalog aggregateCatalog = new AggregateCatalog();//声明一个集合 AssemblyCatalog assemblyCatalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());//声明当前应用程序的cataLog aggregateCatalog.Catalogs.Add(assemblyCatalog);//将当前应用程序的catalog加入到该集合中 CompositionContainer compositionContainer = new CompositionContainer(aggregateCatalog);//声明一个容器 compositionContainer.ComposeParts(this);//创建组件 } [Import("user")] private UserControlTest userControlTest { set; get; } public frmMain() { InitializeComponent(); initMEF();//初始化MEF panel1.Controls.Clear(); panel1.Controls.Add(userControlTest); EventBroker eventBroker = new EventBroker(); eventBroker.Register(userControlTest); eventBroker.Register(this); } [EventSubscription(EventTopics.firstEvent, typeof(Background))] public void receiver(object obj, EventArgs args) { //System.Threading.Thread.Sleep(3000); MessageBox.Show("收到消息了"); } private void timer1_Tick(object sender, EventArgs e) { label1.Text = DateTime.Now.ToString("hh:mm:ss.fff"); } }
2)userControl代码:
[Export("user")] public partial class UserControlTest : UserControl { public UserControlTest() { InitializeComponent(); } [EventPublication(EventTopics.firstEvent)] public event EventHandler testEvent; private void btnTest_Click(object sender, EventArgs e) { testEvent(this,EventArgs.Empty); //System.Threading.Thread.Sleep(3000); } }
3) EventTopics.cs的代码:
public class EventTopics { public const string firstEvent = "test"; }