14 January 2011

.NET - Custom event

Sometimes you need to throw your own custom event with custom arguments. The arguments can be passed directly or by implementing a custom class that inherits from EventArgs. The latter is needed when adding handlers on the event in for instance XAML. The event can be e.g.:

public delegate void ValidationEventHandler(object sender, ValidationEventArgs e);
public event ValidationEventHandler Validation;
protected virtual void OnValidation(string propertyName, bool isValid, string message) {
  if (Validation != null)
    Validation(this, new ValidationEventArgs(propertyName, isValid, message));
}

Which can then be raised by:

OnValidation("Code", false, "Value must not be empty.");

Or you skip the helper method. Make sure the event is not null, meaning there are no listeners:

Validation?.Invoke(this, new ValidationEventArgs(nameof(Code), false, "Value must not be empty."));

You can also use the generic delegate. It can be invoked the same way.

public event EventHandler<ValidationEventArgs> Validation;

No comments:

Post a Comment