Winforms将选项卡页从子窗体添加到父窗体



我想从父表单中的其他表单添加新标签页。

我的父表单MainWindow,此表单具有TabControl。 我有子表单ChildForm当我单击子表单按钮时,我想从MainWindowTabControl添加新标签页。

我尝试在ChildForm中创建构造函数依赖项

private MainWindow mainWindow;   
public List(MainWindow form)
{
this.mainWindow = form;
}
private void createButton_Click(object sender, EventArgs e)
{
TabPage tabPage = new TabPage("ASD");
mainWindow.MainTabControl.TabPages.Add(tabPage);
}

这会抛出System.NullReferenceException

我还尝试创建MainWindow访问器女巫将在MainWindow中返回mainTabControl访问权限,但也不能正常工作。

public static TabControl MainTabControl
{
get {
MainWindow self = new MainWindow();
return self.mainTabControl;
}
}

这不起作用,因为我创建新的参考,这是问题。

我尝试了 2 个示例,但都不起作用,我知道 whay 不起作用!!

有谁知道任何其他人如何解决这个问题?

更好的方法是将创建新选项卡页的任务留给主窗口,并且不让子窗体知道主窗口的任何内部详细信息。子窗体公开一个事件,当他们想要通知其父窗体是时候创建新的选项卡页(或 MainWindow 想要执行的任何操作)时,它们将引发该事件。主窗口订阅此事件,并在请求时开始创建新标签页。

public class ListForm: Form
{
public delegate void OnNewTabPage(string key);
public event OnNewTabPage NewTabPage;
public ListForm()
{
.....
}
private void createButton_Click(object sender, EventArgs e)
{
// Here we pass to the subscriber of the event just a string as 
// the delegate requires, but, of course, you could change this 
// to whatever data you wish to pass to the mainwindow 
// Event a reference to an instance of a class with many fields...
NewTabPage?.Invoke("ASD");
}
}

主窗体中的代码

ListForm f = new ListForm();
f.NewTab += CreateTabPage;
f.Show();
private void CreateTabPage(string key)
{
TabPage page = new TabPage(key);
this.TabControl.TabPages.Add(page);
}

最新更新