我为 Windows 窗体创建了一个自定义用户控件,其操作类似于按钮(请不要建议我只使用按钮,因为我将在此用户控件中存储数据),但我不能弄清楚如何让OnClick()
事件触发。我已经筛选了一些教程并查看了网站上的一些类似问题,但我似乎无法让事件触发 - 所以我要么做错了,要么每个人都发布了不正确的代码(我希望不是后者)
在我的自定义 control.cs 中,
namespace MobCreator {
public partial class MOBSample : UserControl {
public MOBSample() {
InitializeComponent();
}
protected override void OnMouseUp(MouseEventArgs e) {
this.BorderStyle = BorderStyle.FixedSingle;
base.OnMouseUp(e);
}
protected override void OnMouseDown(MouseEventArgs e) {
this.BorderStyle = BorderStyle.Fixed3D;
base.OnMouseDown(e);
}
public event EventHandler ButtonClick;
private void OnButtonClick(object sender, EventArgs e) {
// invoke UserControl event here
if (this.ButtonClick != null) this.OnButtonClick(sender, e);
}
}
}
在我的 form.cs 中,
private void MobCreatorForm_Load(object sender, EventArgs e) {
UserControl1.ButtonClick += new EventHandler(this.CustomEvent_Handler);
}
private void CustomEvent_Handler(object sender, EventArgs e) {
Console.WriteLine("Click");
}
但是,当我运行程序时,我的控制台从不输出“Click”。