如何在具有多个相同控件的表单上实现接口?

时间:2012-05-08 17:18:11

标签: c# events button interface

好的,所以我构建了一个处理所见即所得编辑的自定义控件。基本上在1个控件上我有多个wysiwyg编辑器实例。因此,一个人可能会进行编辑,比如一个食谱。另一个可能是该食谱的注释。

我的wysiwyg编辑器上有一个按钮,它使用一个接口来对控件进行回调,同时保存它们,所以当我点击按钮时,我知道我的父控件。如何找出哪个控件触发了回调?

实施例

主要表格

public partial class MyCustomControl: RecipeControl.ISavedButton {

    private void SaveButton_Clicked(){
        //Do Work but how do I find out which control fired this event?
        //Was it RecipeControl1 or RecipeControl2
    }

}

我的解决方案

在我的食谱控制上,我做到了。

private void RecipeSaveButton_Clicked(object sender, EventArgs e){
    if (RecipeSaveButtonListener != null) {
        RecipeSaveButtonListener.RecipeSaveButton_Clicked(this, EventArgs.Empty); //This referring to the control, not the button.
    }
}

在我的主要控制下,我做到了。

private void RecipeSaveButton_Clicked(object sender, EventArgs e){
    if (sender == RecipeControl1){ 

    } else if (sender == RecipeControl2) { 

    }
}

我已经实现了两个答案,两者都非常好。对不起,我不能接受他们两个。

2 个答案:

答案 0 :(得分:2)

大多数事件处理程序(如按钮单击)都是使用标准界面构建的,以告诉您执行操作的人员。为RecipeControl's按钮点击事件获取“事件处理程序”的修改版本:

 private void SaveButton_Clicked(object sender, EventArgs e){
        //Do Work but how do I find out which control fired this event?
        RecipeControl ctl = sender as RecipeControl;
    }

因此,当您在RecipeControl中点击按钮时,它应触发类似以下事件:

this.SaveButtonClick(this, EventArgs.Empty);

答案 1 :(得分:2)

按照设计,所有事件处理程序都会收到两个参数:

  • object sender:引用引发事件的对象
  • EventArgs e:EventArgs或从EventArgs派生的专门类,具体取决于事件类型

通常,不同的事件处理程序附加到单个控件,因此您不必担心发件人。但是,在您的情况下,您似乎正在为所有控件使用相同的处理程序。在这种情况下,您必须根据发件人做出不同的事情。

为此,您需要检查发件人是否是您感兴趣的发件人,如下所示(我假设按钮名称为Button1)

public ButtonClick(object sender, EventArgs e)
{
    if (sender== RecipeControl1.Button1)
    {
    }
    else if (sender == RecipeControl2.Button1)
    {
    }
}