![](/img/trans.png)
[英]How do I subscribe to an event in a class from another static class?
[英]Mouse Event from one class, how do I listen for it in another class?
我在窗体上有一个UserControl,当我在该UserControl上进行MouseMove移动时,我想在窗体中做一些事情。
如何使该活动的表单“监听”?
我正在使用Visual C#、. Net Framework 3.5,winforms
我想您指的是使用控件或类似的控件。
您可以添加一个public event
,并在检测内部类事件时在您的类内部触发它。
然后,您必须订阅第二堂课中的已发布事件。
这是一个示例,以便您看到正弦值:
public class WithEvent
{
// this is the new published event
public EventHandler<EventArgs> NewMouseEvent;
// This handles the original mouse event of the inner class
public void OriginalEventhandler(object sender, EventArgs e)
{
// this raises the published event (if susbcribedby any handler)
if (NewMouseEvent != null)
{
NewMouseEvent(this, e);
}
}
}
public class Subscriber
{
public void Handler(object sender, EventArgs e)
{
// this is the second class handler
}
public void Subscribe()
{
WithEvent we = new WithEvent();
// This is how you subscribe the handler of the second class
we.NewMouseEvent += Handler;
}
}
如果您在谈论Windows Forms
(问题尚不清楚),则需要在该类中定义一个接收鼠标事件的新事件。 接收后,它将引发一个新的自定义事件。 另一类订阅了(自定义事件)接收通知。
有关moe的信息(不是几行可以介绍的内容),可以在这里查看:
如果您在谈论WPF
,则有不同的事件概念:事件路由。 如果您的类是在实际上接收鼠标事件的组件的UI树中存在的UI元素,它也将传播到您的类。 因此,无需更多编码。
为了进一步说明JotaBe的答案,我可以看到两种情况:
a)类A调用类B中的方法,并且发生异常。 在这种情况下,您无需执行任何操作:异常将遍历堆栈,直到找到catch语句为止。 因此,实际上,您要做的就是不捕获异常,或者如果确实需要捕获异常(出于日志记录等目的),则将其重新抛出。
b)如果由于异常而需要在某个不相关的类中触发代码,那么最好的方法是使用事件。 在您的课程中声明:
public class ClassA
{
public static event EventHandler<Exception> OnException;
public void Notify(Exception ex)
{
if (OnException != null)
{
OnException(this, ex);
}
}
}
然后,为了得到通知,您所需要做的就是
ClassA.OnException += (sender, exeption) =>
{
... some GetHashCode ..
};
...我猜JotaBe在输入时已经添加了所有必要的示例代码
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.