![](/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.