[英]C# Custom click event that not inherit from Control
我可以实现一个自定义单击事件,该事件在用户单击我的对象时引发。
我的对象没有继承任何类,但是具有Location Width Height属性。
问题是:我不知道创建MyObj时如何订阅单击事件的代码。
public delegate void CusEventHandler(object sender, CusEventArgs e);
public class MyObject
{
private Point location;
private int width;
private int height;
public event CusEventHandler Click;
public MyObject(Point loc, int w, int h)
{
this.location = loc;
this.width= w;
this.height= h;
}
protected virtual void OnClick(CusEventArgs e)
{
if (Click != null)
{
Click(this, e);
}
}
}
public partial class Form1 : Form
{
public MyObject myObj;
public Form1()
{
InitializeComponent();
myObj = new (new Point(5,5),100,100);
myObj.Click+= new CusEventHandler(myObj_click);
}
private void myObj_click(object sender,CusEventArgs e)
{
//Some logic
}
}
建议您从Control继承类,这样就已经为您完成了命中测试。 另请参阅这篇文章。
如果您无法复制System.Windows.Controls.Button
等可单击控件中使用的逻辑,那么您将无法做到这一点。 你必须从它提供了一个控制继承Click
-event。 这就是为什么存在继承,并且大多数控件都提供了从它们继承的原因。
另外,如果您的控件确实继承自System.Windows.Controls.Control
类的基类,则您也无法在Windows中使用它。
看这里 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.