2017-07-22 93 views
-1

我試圖爲我的用戶控件實現一個事件處理程序,當用戶控件或用戶控件本身內的任何控件被單擊時觸發點擊。將所有UserControl的控件的單擊事件綁定到父控件上的單個事件

public event EventHandler ClickCard 
{ 
    add 
    { 
     base.Click += value; 
     foreach (Control control in GetAll(this, typeof(Control))) 
     { 
      control.Click += value; 
     } 
    } 
    remove 
    { 
     base.Click -= value; 
     foreach (Control control in GetAll(this, typeof(Control))) 
     { 
      control.Click -= value; 
     } 
    } 
} 
public IEnumerable<Control> GetAll(Control control, Type type) 
{ 
    var controls = control.Controls.Cast<Control>(); 

    return controls.SelectMany(ctrl => GetAll(ctrl, type)) 
             .Concat(controls) 
             .Where(c => c.GetType() == type); 
} 

我修改給定here結合所有嵌套控制的代碼。這是我怎麼綁定在其上使用該用戶控件的事件:

private void feedbackCard1_ClickCard_1(object sender, EventArgs e) 
{ 
    MessageBox.Show("Thank You!"); 
} 

但是點擊不開火點擊用戶控件或用戶控件本身內部的任何控件。

+0

沒有任何解釋接近的選票。爲什麼?請解釋。 –

回答

0

好吧,我想通了,這樣做的另一種方式:

Action clickAction; 
public Action CardClickAction 
{ 
    get 
    { 
     return clickAction; 
    } 
    set 
    { 
     Action x; 
     if (value == null) 
     { 
      x =() => { }; 
     } 
     else 
      x = value; 
     clickAction = x; 
     pictureBox1.Click += new EventHandler((object sender, EventArgs e) => 
     { 
      x(); 
     }); 
     label2.Click+= new EventHandler((object sender, EventArgs e) => 
     { 
      x(); 
     }); 
     tableLayoutPanel3.Click += new EventHandler((object sender, EventArgs e) => 
       { 
      x(); 
     }); 
    } 
} 

現在我們可以使用此用戶控件這樣的形式使用CardClickAction屬性:

Card1.CardClickAction = new Action(() => 
{ 
    //your code to execute when user control is clicked 
}); 
相關問題