如何从List< control >访问更派生的控件类的属性?
本文关键字:派生 控件 属性 访问 List control | 更新日期: 2023-09-27 18:18:03
我发现我不能将Image
属性用于List<Control>
中的PictureBox
控件。
我想这样做:
List<Control> pictureboxes = new List<Control>();
private void button1_Click(object sender, EventArgs e)
{
foreach (var picturebox in pictureboxes)
{
picturebox.Image = WindowsFormsApplication1.Properties.Resources.image;
}
}
我可以这样做吗?
当您将PictureBox
控件放置在List<Control>
容器中时,您无法访问Image
属性的原因是因为列表的基本类型(Control
)没有Image
属性。
属性并没有消失。您只需要将对象从Control
强制转换为更派生的类PictureBox
。然后你可以调用任何方法或访问任何你想要的属性。例如:
List<Control> MyList = new List<Control>();
private void button1_Click(object sender, EventArgs e)
{
foreach (Control ctrl in MyList)
{
// Try to cast the Control object to a PictureBox
PictureBox picBox = ctrl as PictureBox;
if (picBox != null)
{
picBox.Image = WindowsFormsApplication1.Properties.Resources.image;
}
}
}