gpt4 book ai didi

c# - 如何将属性附加到自定义事件?

转载 作者:行者123 更新时间:2023-11-30 13:42:08 26 4
gpt4 key购买 nike

我有一个自定义事件并想为其附加一个属性(一个字符串就可以)。我的代码需要更改什么:

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

最佳答案

首先,您需要创建一个包含新属性的新 RoutedEventArgs 派生类。像这样的东西:

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

然后,您必须创建一个使用新事件参数的委托(delegate):

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

之后,您必须对上面的代码进行更改,以便它使用这些新对象:

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

关于c# - 如何将属性附加到自定义事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3779674/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com