从一个类重用代码到另一个类

本文关键字:另一个 代码 一个 | 更新日期: 2023-09-27 18:12:00

我有两个winforms称为AppNamespace.MYFormAnotherNamespace.AnotherForm
它们都有一个按钮。

当用户点击AnotherNamespace.AnotherForm的按钮时,我想执行点击位于AppNamespace.MYForm的按钮。

但是,AnotherNamespace不能使用AppNamespace
这可以防止我执行以下操作:

AppNamespace.MYForm firstForm = new AppNamespace.MYForm();
firstForm.button.PerformClick();

任何想法?

从一个类重用代码到另一个类

在helper类/另一个名称空间中分隔按钮单击代码,并在按钮单击中调用它。

您可以通过调用helper命名空间和方法在任何命名空间中使用该方法。

手动执行任何控件的事件都是不好的做法。创建单独的方法并执行它。

您可以创建接口,然后将其实现到两个窗体。接口应该包含一个方法PerformClick

public Interface IMyInterface
{
    void PerformClick(string _module);
}
public class Form1 : IMyInterface
{
   public void IMyInterface.PerformClick(string _module) 
   {
      //CODE HERE
      if (Application.OpenForms["Form2"] != null && _module != "Form2")
          ((IMyInterface)Application.OpenForms["Form2"]).PerformClick(_module);
   }
   private void button1_Click(object sender, EventArgs e)
   {
       this.PerformClick(this.Name);
   }
}

public class Form2 : IMyInterface
{
   public void IMyInterface.PerformClick() 
   {
      //CODE HERE
      if (Application.OpenForms["Form1"] != null && _module != "Form1")
          ((IMyInterface)Application.OpenForms["Form1"]).PerformClick(_module);
   }
   private void button1_Click(object sender, EventArgs e)
   {
       this.PerformClick(this.Name);
   }
}

通过编辑Form2.Designer.cs:

Button设置为第二个表单public
public System.Windows.Forms.Button button1;

并将其Click注册到1st Form:

private void Form1_Load(object sender, EventArgs e)
{
    // or whatever you do to create the 2nd form..
    AnotherNamespace.Form2 F2 = new AnotherNamespace.Form2();
    F2.Show();
    // register the click:
    F2.button1.Click += button2_Click;
}

或者以第二种形式创建一个Property:

public Button myButton { get; set;  }

设置为Button:

public Form2()
{
   InitializeComponent();
   myButton = button1;
}

现在你可以像这样注册它的Click:

F2.myButton.Click += button2_Click;