2011-11-25 51 views
0

我想要獲取點擊事件Button,該事件位於我的UserControl中,並且我在表單中動態添加UserControl。我希望事件在Form中提出,我在其中添加UserControl。如果任何人都可以建議我適當的方式,那麼它會非常有幫助。從UserControl的動態添加按鈕中獲取事件

回答

0

將您自己的活動添加到您的自定義用戶控件中。

在你的客戶用戶控件裏面,一旦你添加了按鈕,你還可以附加你的(內部)事件處理程序,然後用某種方式告訴事件處理程序你的(公開的)事件處理程序,可能需要你自己的代表)。

完成後,表單可以添加自己的事件處理程序,就像添加標準控件一樣。

重讀你的問題,這可能不是確切的結構(該按鈕是固定的,而是動態地添加用戶控件?)。無論如何,它應該幾乎相同,只是在創建時添加事件處理程序的地方不同。


有了一個靜態的按鈕,它是一個更容易做 - 假設你使用正在Windows窗體:

在您的自定義用戶控件:

public event EventHandler ButtonClicked; // this could be named differently obviously 

... 

public void Button_OnClick(object sender, EventArgs e) // this is the standard "on button click" event handler created using the form editor 
{ 
    if (ButtonClicked != null) 
     ButtonClicked(this, EventArgs.Empty); 
} 

在您的形式:

// create a new user control and add the event 
MyControl ctl = new MyControl(); 
Controls.Add(ctl); 
ctl.ButtonClicked += new EventHandler(Form_OnUserControlButtonClicked); // name of the event handler in your form that's called once you click the button 

... 

private void Form_OnUserControlbuttonClicked(object sender EventArgs e) 
{ 
    // do whatever should happen once you click the button 
} 
+0

哎馬里奧日Thnx爲replyn你長了什麼,我究竟want.My按鈕固定在我的usercontrol.Only我加入用戶控件dynamically.please你能給我什麼ü解釋了一些例子。 – Deepashri

+0

擴展了答案。沒有對它進行測試,所以可能會出現一些小錯誤,但應該在大方向上提示你。 – Mario

+0

嘿馬里奧我試着實現你的建議,但我得到ButtonClicked爲null在這一行 - 如果(ButtonClicked!= null) ButtonClicked(this,EventArgs.Empty);因此可能是因爲這種形式的事件沒有被調用。有什麼我失蹤....? – Deepashri

0
  1. 當你是加入你的usercontrolform,註冊click事件(如果是publicusercontrol.button.Click += new EventHandler(usercontrolButton_Click);

  2. 內的usercontrol

+1

這假設你的按鈕控制是公開的... –

2

註冊按鈕的Click事件中,我猜你正在使用的WinForms指你的標題。

你可以做什麼來轉發你的Click事件。

所以在您的用戶控件

public class MyUserControl 
{ 
    public event EventHandler MyClick; 
    private void OnMyClick() 
    { 
     if (this.MyClick != null) 
      this.MyClick(this, EventArgs.Empty); 
    } 
    public MyUserControl() 
    { 
     this.Click += (sender, e) => this.OnMyClick(); 
    } 
} 
3

的構造函數你需要在你的用戶控件暴露事件,然後訂閱它,當您添加用戶控件到窗體。例如: -

public partial MyUserControl:Control 
{ 
    public event EventHandler ButtonClicked; 
    private void myButtonClick(object sender, EventArgs e) 
    { 
     if (this.ButtonClicked != null) 
     this.ButtonClicked(this, EventArgs.Empty); 
    } 
} 

public partial MyForm:Form 
{ 
    private void MethodWhereYouAddTheUserControl() 
    { 
     var myUC = new MyUserControl(); 
     myUC += myUC_ButtonClicked; 
     // code where you add myUC to the form... 
    } 

    void myUC_ButtonClicked(object sender, EventArgs e) 
    { 
     // called when the button is clicked 
    } 
} 
+0

嘿是這個私人無效myButtonClick(對象發件人,EventArgs e) 單擊usercontrol中的按鈕事件,我需要在我的winform中引發事件? – Deepashri

+0

@Deepashri:是的,它是:) – digEmAll

+0

thnx @digEmAll :) – Deepashri

相關問題