How to attach a property to a custom event?

I have a custom event and I want to add a property (the string will be fine). What I need to change in my code:

    public static readonly RoutedEvent ModelClickEvent = EventManager.RegisterRoutedEvent(
        "ModelClick", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(InfoBox));

    // Provide CLR accessors for the event
    public event RoutedEventHandler FadeIn
    {
        add { AddHandler(ModelClickEvent, value); }
        remove { RemoveHandler(ModelClickEvent, value); }
    }

    // This method raises the Tap event
    void RaiseTapEvent()
    {
        RoutedEventArgs newEventArgs = new RoutedEventArgs(InfoBox.FadeInEvent); 
        RaiseEvent(newEventArgs);
    }
+3
source share
2 answers

First you need to create a new class based on RoutedEventArgs containing your new property. Sort of:

public class ModelClickEventArgs : RoutedEventArgs
{
    public string MyString { get; set; }
    public ModelClickEventArgs() : base() { }
    public ModelClickEventArgs(RoutedEvent routedEvent) : base(routedEvent) { }
    public ModelClickEventArgs(RoutedEvent routedEvent, object source) : base(routedEvent, source) { }
}

Then you need to create a delegate that uses your new event arguments:

public delegate void ModelClickEventHandler(object sender, ModelClickEventArgs e);

After that, you will have to make changes to your code above to use these new objects:

public static readonly RoutedEvent ModelClickEvent = EventManager.RegisterRoutedEvent(
        "ModelClick", RoutingStrategy.Bubble, typeof(ModelClickEventHandler), typeof(Window));

// Provide CLR accessors for the event
public event ModelClickEventHandler FadeIn
{
    add { AddHandler(ModelClickEvent, value); }
    remove { RemoveHandler(ModelClickEvent, value); }
}

// This method raises the Tap event
void RaiseTapEvent()
{
    ModelClickEventArgs newEventArgs = new ModelClickEventArgs();
    newEventArgs.MyString = "some string";
    RaiseEvent(newEventArgs);
}
+8
source

RoutedEventArgs, , , RoutedEventArgs, (-y/-ies), .

:

public class ModelRoutedEventArgs : RoutedEventArgs
{
  public string ExtraMessage { get; set; }
  public ModelRoutedEventArgs(RoutedEvent routedEvent, string message) : base(routedEvent)
  {
    ExtraMessage = message;
  }
  // anything else you'd like to add can go here
}

RoutedEventArgs RaiseEvent().

+2

Source: https://habr.com/ru/post/1766241/


All Articles