2014-09-13 29 views
-1

我想,當一個標籤背景色改爲執行一段代碼..運行用戶控件的代碼

以下是代碼

private void lbl_ps_BackColorChanged(object sender, EventArgs e) 
    { 
     if (lbl_ps.BackColor == Color.Green) 
     { 
      menu_ctrl.setup_array = str_array; 
      indx = 0; 
     } 
    } 

這裏「menu_ctrl」是一個用戶控件,其中這setup_array由下面的代碼的

public string[] setup_array 
    { 
     get 
     { 
      return list_array; 
     } 

     set 
     { 
      list_array = value; 
      setup_list(value); 
     } 
    } 

private void setup_list(string[] list_item) 
    { 
     //this.Width = 266; 
     this.Height = 181; 
     for (int i = 0; i < n; i++) 
     { 
      this.Controls.Remove(labels[i]); 
     } 
     label1.Visible = false; 
     this.BorderStyle = BorderStyle.None; 
     indx_abs = 0; indx_rel = 0; 
     n = list_item.Length; 

     Array.Resize(ref labels, n); 

     for (int i = 0; i < n; i++) 
     { 
      labels[i] = new CustomText(); 
      labels[i].Left = 20; 
      labels[i].Top = ((30) * i)+1; 
      labels[i].IsSelected = false; 
      this.Controls.Add(labels[i]); 
      labels[i].Text = list_item[i]; 
     } 

     labels[indx_abs].IsSelected = true; 
    } 

但代碼不會執行....它工作正常,如果我打電話從一個按鈕單擊事件的代碼..但它在backcolorchange不會執行事件

有幫助嗎?

編輯:我試圖破發點和我setup_list功能

Cross-thread operation not valid: Control 'CustomText' accessed from a thread other than the thread it was created on. 

得到了在第一個for循環該錯誤的錯誤被抓深我一直在使用的參考DLL內。順便說一句在這個DLL的功能是引發這種顏色變化事件

回答

0

感謝@Nati Dobkin!

我能夠識別代碼觸發器正在創建一個新的線程..並發現這在互聯網上強制運行在主線程中的代碼。

this.Invoke(new MethodInvoker(() => 
      { 
       //run your code here 
      })); 
0

基本上你的代碼是正確的,它對我來說工作得很好。我會檢查是兩件事情

1)事件實際上是附着,搜索你的代碼爲

this.lbl_ps.BackColorChanged + =新System.EventHandler(this.lbl_ps_BackColorChanged);

2)正被引發的事件,地方在你的代碼,你必須

lbl_ps.BackColor = Color.Green; //或任何其他顏色。

+0

我知道它的作品!但不完全如果我刪除「menu_ctrl.setup_array = str_array;」並寫一個標籤文本更改代碼它的作品,但不是這個usercontrol代碼...我不知道笏做它顯示沒有任何錯誤..它只是不工作 – 2014-09-13 18:48:16

+0

你有沒有在代碼上放一些斷點?在哪一行停止執行? – 2014-09-13 20:55:33

+0

謝謝你..我試過了斷點,並且在setup_list函數的第一個for循環中出現了這個錯誤 '跨線程操作無效:控制'CustomText'從其創建線程以外的線程訪問。 ' 錯誤被深藏在我一直使用的引用dll內部。順便說一句在這個DLL中的函數是引發這個colorchanged事件 – 2014-09-14 05:19:32