views:

35

answers:

2

I have a custom event and want to attach a property (a string would be fine) to it. What do 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);
    }
+2  A: 

First, you'll need to create a new RoutedEventArgs-derived class containing your new property. Something like:

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'll have to create a delegate that uses your new event args:

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

After that, you will have to make changes to your code above so that it uses 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);
}
karmicpuppet
+2  A: 

If you mean that you'd like to add a property to the RoutedEventArgs object that the handlers receive, then all you'd have to do is declare a class that inherits from RoutedEventArgs and has the propert(-y/-ies) you'd like to add.

It would look something like the following:

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
}

Or, instead of adding a constructor overload, you can just instantiate your custom RoutedEventArgs class and set the property before passing it to the RaiseEvent() call.

Eric
It seems you can't the constructor like that: base(RoutedEvent); It keeps saying "Usage of the base-command in this context is not possible.
Hedge
OK. I'll edit my answer. Looks like you can chain the constructor call.
Eric