C# event with custom arguments
EventHandler
receives EventArgs
as a parameter. To resolve your problem, you can build your own MyEventArgs
.
public enum MyEvents
{
Event1
}
public class MyEventArgs : EventArgs
{
public MyEvents MyEvent { get; set; }
}
public static event EventHandler<MyEventArgs> EventTriggered;
public static void Trigger(MyEvents ev)
{
if (EventTriggered != null)
{
EventTriggered(null, new MyEventArgs { MyEvent = ev });
}
}
You declare a delegate for the parameters:
public enum MyEvents { Event1 }
public delegate void MyEventHandler(MyEvents e);
public static event MyEventHandler EventTriggered;
Although all events in the framework takes a parameter that is or derives from EventArgs
, you can use any parameters you like. However, people are likely to expect the pattern used in the framework, which might make your code harder to follow.
I might be late in the game, but how about:
public event Action<MyEvent> EventTriggered = delegate { };
private void Trigger(MyEvent e)
{
EventTriggered(e);
}
Setting the event to an anonymous delegate avoids for me to check to see if the event isn't null.
I find this comes in handy when using MVVM, like when using ICommand.CanExecute Method.