开发者

How do i attach property to a custom event?

开发者 https://www.devze.com 2023-01-17 03:13 出处:网络
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:

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.Regist开发者_运维问答erRoutedEvent(
        "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);
    }


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);
}


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消