【发布时间】:2018-08-20 12:44:07
【问题描述】:
我有一个主窗体 (form1),它有一个面板 (panel1) -- 见图。
Panel1 根据按下的按钮加载两个不同的用户控件之一(以模拟屏幕变化)。我在用户控件 1 上有一个按钮,需要在用户控件 2 上操作(更改文本)。
我遇到的问题是用户控件是通过在表单 1 上按下按钮动态创建的(参见下面的代码),这导致我在尝试链接事件时出现问题-
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
panel1.Controls.Add(new Screens.UC1());
}
private void button1_Click(object sender, EventArgs e)
{
foreach (Control ctrl in panel1.Controls)
{
ctrl.Dispose();
}
panel1.Controls.Add(new Screens.UC1());
}
private void button2_Click(object sender, EventArgs e)
{
foreach (Control ctrl in panel1.Controls)
{
ctrl.Dispose();
}
panel1.Controls.Add(new Screens.UC2());
}
}
当动态创建对象的实例时,处理将这些类型的项目与事件链接的最佳方法是什么。我还尝试创建屏幕实例,然后引用这些实例,但这遇到了范围问题。
UC1 的代码(用户控件 1)
public partial class UC1 : UserControl
{
public UC1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
//Event to change text on UC2
}
}
UC2 代码(用户控制 2)
public partial class UC2 : UserControl
{
public UC2()
{
InitializeComponent();
}
public void WriteText(object sender, EventArgs e)
{
label2.Text = "Text Changed...";
}
}
非常感谢任何帮助。
【问题讨论】: