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.
You need to declare a custom eventhandler.
public class MyEventArgs: EventArgs
{
...
}
public delegate void MyEventHandler(object sender, MyEventArgs e);
public class MyControl: UserControl
{
public event MyEventHandler MyEvent;
...
}
Here's a reworking of your sample to get you started.
your sample has a static event - it's more usual for an event to come from a class instance, but I've left it static below.
the sample below also uses the more standard naming OnXxx for the method that raises the event.
the sample below does not consider thread-safety, which may well be more of an issue if you insist on your event being static.
.
public enum MyEvents{
Event1
}
public class MyEventArgs : EventArgs
{
public MyEventArgs(MyEvents myEvents)
{
MyEvents = myEvents;
}
public MyEvents MyEvents { get; private set; }
}
public static class MyClass
{
public static event EventHandler<MyEventArgs> EventTriggered;
public static void Trigger(MyEvents myEvents)
{
OnMyEvent(new MyEventArgs(myEvents));
}
protected static void OnMyEvent(MyEventArgs e)
{
if (EventTriggered != null)
{
// Normally the first argument (sender) is "this" - but your example
// uses a static event, so I'm passing null instead.
// EventTriggered(this, e);
EventTriggered(null, e);
}
}
}