使用事件和公共属性,因为听起来您在设计器中添加每个项目,然后您可以连接您的事件处理程序并访问您的用户控件中的属性,为其分配一个名称,以便您以后可以找到它。这是一个非常粗略的例子,看看它对你有用。
用户控制
public partial class MyCustomUserControl : UserControl
{
public event EventHandler<EventArgs> MyCustomClickEvent;
public MyCustomUserControl()
{
InitializeComponent();
}
public bool CheckBoxValue
{
get { return checkBox1.Checked;}
set { checkBox1.Checked = value; }
}
public string SetCaption
{
get { return groupBox1.Text;}
set { groupBox1.Text = value;}
}
private void button1_Click(object sender, EventArgs e)
{
MyCustomClickEvent(this, e);
}
}
表格1
public partial class Form1 : Form
{
int count =1;
public Form1()
{
InitializeComponent();
}
private void mcc_MyCustomClickEvent(object sender, EventArgs e)
{
((MyCustomUserControl)sender).CheckBoxValue = !((MyCustomUserControl)sender).CheckBoxValue;
}
private void button1_Click(object sender, EventArgs e)
{
MyCustomUserControl mcc = new MyCustomUserControl();
mcc.MyCustomClickEvent+=mcc_MyCustomClickEvent;
mcc.Name = "mmc" + count.ToString();
mcc.SetCaption = "Your Text Here";
flowLayoutPanel1.Controls.Add(mcc);
count += 1;
}
private void button2_Click(object sender, EventArgs e)
{
var temp = this.Controls.Find("mmc1", true);
if (temp.Length != 0)
{
var uc = (MyCustomUserControl)temp[0];
uc.SetCaption = "Found Me";
}
}
}