私はuserControl1という名前のuserControlを作成しています。このユーザーコントロールでは、ボタン名はbtnAddです。私はForm1とForm2の2つのフォーム名を作成します。そして、それらのフォームにUserControl1を追加します。 Form1のbtnAddボタンをクリックしてからForm2にbtnAddボタンをクリックすると文字列 "this is form 1"が表示され、 "this is form 2"という文字列が表示されます。userControlでdelegateとeventを使用するには?
これを行うには、委任とイベントを使用します。私たちを手伝ってくれますか。 ありがとうございます。
次のコードは実行されますが、実行されません。正しい結果がメッセージボックス「成功しました」に表示される必要があります。
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;
namespace EventDelegateUserControl
{
public partial class UC_them : UserControl
{
public UC_them()
{
InitializeComponent();
}
public delegate void ThemClickHandler(object sender, EventArgs e);
public event ThemClickHandler ThemClick;
public void OnThemClick(EventArgs e)
{
if (ThemClick != null)
{
ThemClick(this,e);
}
}
public void add()
{
OnThemClick(EventArgs.Empty);
}
public void btnThem_Click(object sender, EventArgs e)
{
add();
}
}
//---------------------------
public partial class Form1 : Form
{
public UC_them uc_them =new UC_them();
public Form1()
{
InitializeComponent();
}
public void dangky(UC_them uc_them)
{
uc_them.ThemClick += new UC_them.ThemClickHandler(uc_them_ThemClick);
}
void uc_them_ThemClick(object sender, EventArgs e)
{
MessageBox.Show("Add successful");
}
}
//----------------------------
static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
UC_them them = new UC_them();
Form1 form1 = new Form1();
form1.dangky(them);
}
}
}