简体   繁体   中英

Why is my event always null even though it is properly added at the calling function?

(Info): I know this has been asked several times, but IMHO always the issue was that the Event wasn't really added at the calling funcation, which is not the case here.

I have the following class:

 public class FilePanel : BasePanel
{
    public event LinkClickedEventHandler FileOpen;
    private PlaylistElement _element;

    public FilePanel() : base()
    {
        AddControls(new PlaylistElement { Description = "lorem ipsom" });
    }

    public FilePanel(PlaylistElement element) : base(element)
    {
        AddControls(element);
    }

    private void AddControls(PlaylistElement element)
    {
        _element = element;
        ToolTip tt = new ToolTip();
        var textControl = new Label { Dock = DockStyle.Fill, Text = element.File.Title, Padding = new Padding(2, 2, 5, 2) };
        var linkControl = new LinkLabel { Dock = DockStyle.Right, TextAlign= System.Drawing.ContentAlignment.MiddleRight, Width = 200, Text = "Datei öffnen",  Padding = new Padding(2, 2, 5, 2) };
        tt.SetToolTip(linkControl, element.File?.FileReference);
        linkControl.Click += LinkControl_Click;
        this.Controls.Add(textControl);
        base.AddControls(element);
        this.Controls.Add(linkControl);

        this.Height = 50;
    }

    private void LinkControl_Click(object sender, EventArgs e)
    {
        FileOpen?.Invoke(this, new LinkClickedEventArgs(_element.File.FileReference));
    }
}

This class is called the following way:

private void AddScheduleFile(RadCollapsiblePanel blockPanel, PlaylistElement element)
{
    var panel = new ScheduleControls.FilePanel(element);
    panel.FileOpen += Panel_FileOpen;
    blockPanel.Controls.Add(new ScheduleControls.FilePanel(element));
}

As you can see, the FileOpen-Event is assigned to the calling class.

But when I Break into LinkControl_Click , FileOpen is NULL nonetheless.

it seems that you fire the event in the wrong object. Although you register the event you do it for the panel object. But you add an entirely new object to the controls:

blockPanel.Controls.Add(new ScheduleControls.FilePanel(element));

if you now use this object to fire the event, you will see that it is null because you have not registered it. Why not passing the original object to the controls?=! :

private void AddScheduleFile(RadCollapsiblePanel blockPanel, PlaylistElement element)
{
    var panel = new ScheduleControls.FilePanel(element);
    panel.FileOpen += Panel_FileOpen;
    blockPanel.Controls.Add(panel);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM