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

时间:2019-05-26 23:54:53

标签: c# tabpage

我正在为动态创建的Tabpage添加一个事件。但是,当我与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");
    }

1 个答案:

答案 0 :(得分:0)

我已经知道了!

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

初始化事件处理程序

    SourceTabControl.MouseDoubleClick += new MouseEventHandler(SourceTabControl_MouseDoubleClick);

然后

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