[問題] 利用event控制UI

看板C_Sharp作者時間16年前 (2009/07/08 11:06), 編輯推噓1(102)
留言3則, 2人參與, 最新討論串1/1
我是c#初學者 不知這樣的做法對不對.. 一般在Form本身的method裡想要控制UI, 只要呼叫this.BeginInvoke.. 但現在.. 例如我在Form1裡面實體化一個class C 並希望在C裡面的thread執行過程中能去update UI介面 我的作法是這樣 (從MSDN參考來的..) 1. 宣告一個event handler public delegate void RefreshUIEventHandler(object sender, RefreshUIEventArgs e); 2. 在欲控制UI的class C裡面宣告一個event public event RefreshUIEventHandler RefreshUI; 3. 在Form1實體化C的時候,順便將該物件的RefreshUI掛上事件處理常式 C m_c = new C(); m_c.RefreshUI += this.RefreshUIMethod; 4. 最後,實作Form1的RefreshUIMethod (假設要控制的控制項是listBox1) void RefreshUIMethod( object sender, EventArgs e ) { if( this.listBox1.InvokeRequired ) { this.BeginInvoke( new RefreshUIEventHandler( RefreshUIMethod ), new object[] {sender,e}); } else { // 這裡是實際控制UI的Code listBox1.... } } 我就樣做就可以動了.. 只是很多code都是msdn半學半賣加進去的 不知有沒有什麼遺漏或是多餘的地方...或是有比這個更好的方法.. 煩請指教... thanks! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 60.251.164.146 ※ 編輯: asingular 來自: 60.251.164.146 (07/08 11:12)

07/09 20:40, , 1F
我都習慣定一個Interface(類似Listener),實作method再對
07/09 20:40, 1F

07/09 20:41, , 2F
自己寫的Class註冊
07/09 20:41, 2F

07/12 14:30, , 3F
even=event?
07/12 14:30, 3F
sorry.. 拼錯字了 ※ 編輯: asingular 來自: 220.135.204.230 (07/19 08:21)
文章代碼(AID): #1AL0r2Ga (C_Sharp)