2012-03-12 26 views
0

您好我正在创建一个测试应用程序,该用户控件带有一个将在表单中引用的按钮。如何在用户控件中实现接口函数

enter image description here

是否可以绑定接口

public interface ICRUD 
    { 
     void Test(); 
    } 

用户控制Button1的Click事件

public partial class UserControl1 : UserControl 
{ 
    public UserControl1() 
    { 
     InitializeComponent(); 

    } 
    private void button1_Click(object sender, EventArgs e) 
    { 
     //CALL ICRUD.Test() execute when click on form1 and then show I am Clicked 
    } 
} 

使 我只需要只实现接口功能,以我的Form1上。

Form1中:

using System.Windows.Forms; 
namespace TEST 
{ 
    public partial class Form1 : Form , ICRUD 
    { 
     public Form1() 
     { 
      InitializeComponent(); 
     } 

     public void Test() 
     { 
      MessageBox.Show("I am Clicked"); 
     } 
    } 
} 

谢谢关心。

+0

您打算删除多少次并重新提出同一个问题? – 2012-03-12 02:56:08

+0

您可以在ICRUD类型的用户控件中拥有属性,并从表单中设置此属性。 – 2012-03-12 03:00:18

+0

@ M.Babcock感谢您的FAQ。这是我的最后一个问题,先生。和我附上样本图像,使我的问题更清洁.. :) – BizApps 2012-03-12 03:01:46

回答

0

这似乎并不适合我。这可能不是Form应该实现这个接口。更重要的是,界面并没有带来任何东西。

但如果你真的想这样做,你可以访问the ParentForm property,将它转换为你的接口,然后调用方法:

private void button1_Click(object sender, EventArgs e) 
{ 
    var crud = (ICrud)ParentForm; 
    crud.Test(); 
} 

此外,.NET中的惯例是写缩写(至少长的)与其他词相同,所以你应该命名你的界面ICrud

+0

哇!谢谢@ svick ..完美.. – BizApps 2012-03-12 03:14:48

0
private void button1_Click(object sender, EventArgs e) 
{ 
    for(var parent = this.Parent; parent != null; parent = parent.Parent) 
    { 
     var crud = parent as ICRUD; 
     if (crud != null) 
     { 
     crud.Test(); 
     break; 
     } 
    } 
}