所以我仍在学习,因为我去了很多,但我似乎无法弄清楚如何在动态创建的用户控件中访问方法。
我设法让这个工作:
Control picture = new UserControl1();
picture.Visible = true;
picture.Name = "PIC1";
picture.Location = new Point(0, 0);
picture.Show();
flowLayoutPanel1.Controls.Add(picture);
(UserControl1)picture).SetMSG("Test");
但是我希望通过它的名称来解决控件的每个实例:
Control picture = new UserControl1();
picture.Visible = true;
picture.Name = "PIC1";
picture.Location = new Point(0, 0);
picture.Show();
flowLayoutPanel1.Controls.Add(picture);
(UserControl1)PIC1).SetMSG("Test");
我想我可能只是误解了整个概念?
答案 0 :(得分:0)
我想我可能只是误解了整个概念?
是的,你是。你不能只使用那样的控件名称。你可以做:
var PIC1 = flowLayoutPanel1.Controls.Find("PIC1",false);
但您已经拥有对控件的引用(picture
),因此我不需要获取不同的引用。< / p>
答案 1 :(得分:0)
您可以在视图中保留对动态创建的控件的引用:
class MyView
{
public void CreateControl(string name)
{
Control picture = new UserControl1();
picture.Visible = true;
picture.Name = name;
picture.Location = new Point(0, 0);
picture.Show();
flowLayoutPanel1.Controls.Add(picture);
this.controls.Add(name, picture);
}
public void SetMsg(string name, msg)
{
((UserControl1)this.controls[name]).SetMSG(msg);
}
private Dictionary<string, Control> controls = new Dictionary<string, Control>();
}