如何在 C# 中处理动态生成的标签页的事件?

How handle event for dynamically generated tabpages in c#?

我正在为动态创建的标签页添加一个事件。但是,当我与 UI 交互时,不会调用该事件。帮助! :)

我已经在下面尝试过但不起作用:

Event handling for dynamically generated controls

C# TabControl TabPage passing events

    private void FileListView_DoubleClick(object sender, EventArgs e)
    {
        if (FileListView.SelectedIndices != null && FileListView.SelectedIndices.Count > 0)
        {
            FileListViewTask.Expand(settingsForm, FileListView, FileListView.SelectedIndices[0]);
            string filepathSelected=FileListViewTask.getFilePath(FileListView.SelectedIndices[0]);
            if (filepathSelected != "")
            {
                bool tabAlreadyExists = false;
                foreach (TabPage tabpage in SourceTabControl.TabPages)
                {
                    if (tabpage.GetNextControl(new Label(), true).Text == filepathSelected)
                    {
                        SourceTabControl.SelectTab(tabpage);
                        tabAlreadyExists = true;
                        break;
                    }

                }
                if (!tabAlreadyExists)
                {
                    TabPage tabpage = (new CodePageGenerator(filepathSelected)).createPage();
                    tabpage.Parent = SourceTabControl;
                    tabpage.MouseDoubleClick += new MouseEventHandler(tabpage_MouseDoubleClick);
                    tabpage.Click += new EventHandler(this.tabpage_Click);
                    SourceTabControl.SelectTab(tabpage); 
                }
            }
        }
    } 

    void tabpage_Click(object sender, EventArgs e)
    {
        TabPage tabpage = (TabPage)sender;
        SourceTabControl.TabPages.Remove(tabpage);
        MessageBox.Show("yow");
    }

    void tabpage_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        TabPage tabpage = (TabPage)sender;
        SourceTabControl.TabPages.Remove(tabpage);
        MessageBox.Show("yow");
    }

更新

上面的代码在 TabPage 内容中发生点击时起作用。但在单击选项卡时不起作用

我已经想通了!

关键是给TabControl而不是TabPage添加一个事件! 单击选项卡按钮的事件将传递给 TabControl。

初始化事件处理程序

    SourceTabControl.MouseDoubleClick += new MouseEventHandler(SourceTabControl_MouseDoubleClick);

那么,

    private void SourceTabControl_MouseDoubleClick(object sender, MouseEventArgs e)
    {
        SourceTabControl.TabPages.Remove(SourceTabControl.SelectedTab);
    }