如何在C#.net win表单中注册自定义应用程序事件的事件处理程序?
我有一个处理自定义事件的方法 我正在尝试将此方法注册为我的事件的事件处理程序。 处理事件的方法需要在表单中,因为它需要更新表单的属性(listview) 我提出这项活动如下:如何在C#.net win表单中注册自定义应用程序事件的事件处理程序?,c#,asp.net,.net,events,eventhandler,C#,Asp.net,.net,Events,Eventhandler,我有一个处理自定义事件的方法 我正在尝试将此方法注册为我的事件的事件处理程序。 处理事件的方法需要在表单中,因为它需要更新表单的属性(listview) 我提出这项活动如下: // Inside MyForm.cs ApplicationEvents.Raise(new MyCustomEvent(param1, this.listview)); public class MyCustomEventHandler { public static void Registe
// Inside MyForm.cs
ApplicationEvents.Raise(new MyCustomEvent(param1, this.listview));
public class MyCustomEventHandler
{
public static void RegisterMyCustomEventHandler()
{
var handler = new MyCustomEventHandler();
ApplicationEvents.Register<MyCustomEvent>
(handler.HandleMyCustomEvent);
}
public void HandleMyCustomEvent(MyCustomEvent event)
{
//code to handle the event
}
}
//在MyForm.cs中
ApplicationEvents.Raise(新的MyCustomEvent(param1,this.listview));
公共类MyCustomEventHandler
{
公共静态无效注册表myCustomEventHandler()
{
var handler=新的MyCustomEventHandler();
应用程序事件。注册
(handler.HandleMyCustomEvent);
}
公共无效HandleMyCustomEvent(MyCustomEvent事件)
{
//处理事件的代码
}
}
已尝试上述代码,但无法应用于我的上下文,因为我必须在应更新表单控件的任务内引发应用程序事件
正因为如此,我得到了跨线程错误。所以我想我应该在表单代码中移动RegisterMyCustomEventHandler和HandleMyCustomEvent方法。因此,我的问题现在转移到将该方法注册为eventhandler
// inside MyForm class:
public void HandleMyCustomEvent( MyCustomEvent myEvent)
{
// some code to handle the event.
}
// I tried something like this
public void RegisterMyCustomEventHandler()
{
var handler = new MyCustomEventHandler();
ApplicationEvents.Register<MyCustomEvent> (handler.HandleCustomEvent);
}
// Program.cs class:
static void Main(string[]
{
MyCustomEventhandler.RegisterMyCustomEventHandler();
}
// And how I raise the exception:
ApplicationEvents.Raise(new MyCustomEvent(param1, form.listview));
//在MyForm类中:
公共无效HandleMyCustomEvent(MyCustomEvent myEvent)
{
//一些用于处理事件的代码。
}
//我试过这样的东西
公共无效注册表myCustomEventHandler()
{
var handler=新的MyCustomEventHandler();
ApplicationEvents.Register(handler.HandleCustomEvent);
}
//Program.cs类:
静态void Main(字符串[])
{
MyCustomEventhandler.RegisterMyCustomEventHandler();
}
//以及我如何提出例外:
Raise(新的MyCustomEvent(param1,form.listview));