自定义事件初始化问题

时间:2017-02-24 15:49:13

标签: c# events

我在图形对象上使用自定义事件来通知对象的更改:

public class OnLabelWidthChangedEventArgs : EventArgs
{
    private float _width;

    public float Width
    {
        get { return _width; }
        set { _width = value; }
    }

    public OnLabelWidthChangedEventArgs(float widthParam) : base()
    {
        Width = widthParam;
    }
}

这是触发此事件的对象:

public class DisplayLabel : DisplayTextObject
{
    public event EventHandler<OnLabelWidthChangedEventArgs > OnLabelSizeChanged;

    public DisplayLabel(ScreenView _screenParam, IXapGraphicObject obj) : base(_screenParam, obj)
    {
        l = new Label();
        SetSize();
    }

    public override void SetSize()
    {
        Width = w;
        Height = h;
        if(OnLabelWidthChanged != null)
             OnLabelSizeChanged.Invoke(this, new OnLabelWidthChangedEventArgs(w)); //  OnLabelSizeChanged is null
    }

OnLabelSizeChanged始终为空,我该如何初始化它。

我有一个有代表的工作解决方案,而不是自定义事件:

 public event OnWidthChanged WidthChanged = delegate { };

但我想知道如何使用自定义事件解决此问题。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

你没有初始化你的事件,你为它分配一个处理程序(也就是订阅它),类似于:

myDisplayLabel.OnLabelWidthChanged += MyEventHandlerMethod;

其中MyEventHandlerMethod是匹配事件签名的方法,即

void MyEventHandlerMethod(Object sender, OnLabelWidthChangedEventArgs)

睡前阅读:https://msdn.microsoft.com/en-us/library/9aackb16(v=vs.110).aspx

相关问题