2012-09-14 44 views
4

在我的應用程序中,我有一個負責所有數據庫操作的類。它從主類中調用,並在操作完成後使用委託來調用方法。 因爲它是異步的,我必須使用調用我的GUI,所以我創建了一個簡單的擴展方法:InvokeRequired和ToolStripStatusLabel

public static void InvokeIfRequired<T>(this T c, Action<T> action) 
      where T: Control 
     { 
      if (c.InvokeRequired) 
      { 
       c.Invoke(new Action(() => action(c))); 
      } 
      else 
      { 
       action(c); 
      } 
     } 

這工作得很好,當我嘗試調用它的textBox:

textBox1.InvokeIfRequired(c => { c.Text = "it works!"; }); 

但當我嘗試調用它ToolStripStatusLabel或ToolStripProgressBar我得到一個錯誤:

The type 'System.Windows.Forms.ToolStripStatusLabel' cannot be used as type parameter 'T' in the generic type or method 'SimpleApp.Helpers.InvokeIfRequired(T, System.Action)'. There is no implicit reference conversion from 'System.Windows.Forms.ToolStripStatusLabel' to 'System.Windows.Forms.Control'.

我知道這可能是一個簡單的修補程序,但我能應付自如:/

+0

也許這個類似的問題會幫助你。 http://stackoverflow.com/questions/1127973/how-do-i-make-cross-threaded-calls-to-a-toolstripstatuslabel – Rugbertl

回答

8

這是因爲ToolStripItem(導致錯誤的那兩個的基礎)是組件而不是控件。 請嘗試在擁有它們的工具條上調用您的擴展方法,並調整您的代理 方法。

+0

我剛剛從Google上發佈了相同的信息:)但我應該如何訪問ToolStripStatusLable從statusStrip?所以我可以將statusStrip傳遞給我的方法? – Misiu

+1

http://msdn.microsoft.com/en-us/library/system.windows.forms.toolstrip.items.aspx MSDN是你的朋友:) – slawekwin

+0

你很快:)但如何訪問項目?只能通過索引或我可以按名稱來完成?例如,如果我命名ToolStripStatusLabel的'狀態'我如何在我的委託中訪問它?只有像'statusStrip1.Items [0]'?我問,因爲我將動態地添加控件到statusStrip,我可以搞亂我的控件的索引。 – Misiu