標籤:
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"; }
C# 使用MEF動態載入不同的userControl,並實現不同userControl之間通訊