Skip to main content
 首页 » 编程设计

c#之如何在具有多个相同控件的窗体上实现接口(interface)

2024年02月20日29lori

好的,我已经构建了一个处理所见即所得编辑的自定义控件。基本上在 1 个控件上,我有多个所见即所得编辑器的实例。所以一个可能用于编辑,比方说,一个食谱。另一个可能是那个食谱的注释。

我的 wysiwyg 编辑器上有一个按钮,它使用一个接口(interface)对包含它们的控件进行回调,所以我知道我的父控件何时单击了该按钮。我如何找出触发回调的控件?

例子

主窗体

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) {  
 
    } 
} 

我已经实现了这两个答案,而且都非常非常好。抱歉,我不能同时接受它们。

请您参考如下方法:

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

 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);