I followed this tutorial but I couldn't apply what I learned to my project.
I have a LineGraph
object (Dynamic Data Display) and I want to create an event that is raised when the thickness of the LineGraph is equal to 0.
How am I supposed to write it following this tutorial ?
Personally, I usually avoid creating events, preferring instead to create delegate
s. If there is some particular reason that you specifically need an event, then please ignore this answer. The reasons that I prefer to use delegate
s are that you don't need to create additional EventArgs
classes and I can also set my own parameter types.
First, let's create a delegate:
public delegate void TypeOfDelegate(YourDataType dataInstance);
Now a getter and setter:
public TypeOfDelegate DelegateProperty { get; set; }
Now let's create a method that matches the in and out parameters of the delegate
:
public void CanBeCalledAnything(YourDataType dataInstance)
{
// do something with the dataInstance parameter
}
Now we can set this method as one (of many) handlers for this delegate
:
DelegateProperty += CanBeCalledAnything;
Finally, let's call our delegate
... this is equivalent to raising the event:
if (DelegateProperty != null) DelegateProperty(dataInstanceOfTypeYourDataType);
Note the important check for null
. So that's it! If you want more or less parameters, just add or remove them from the delegate
declaration and the handling method... simple.