C# 使用MEF動態載入不同的userControl,並實現不同userControl之間通訊

來源:互聯網
上載者:User

標籤:

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之間通訊

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.