如何从 List访问更派生的控件类的属性?

发布于 2024-12-21 19:33:17 字数 464 浏览 0 评论 0原文

我发现无法在 List 中使用 PictureBox 控件的 Image 属性。

我想做这样的事情:

    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;
        }
    }

我能以某种方式做到这一点吗?

I found that I can't use the Image property for a PictureBox control in List<Control>.

I want to do something like this:

    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;
        }
    }

Can I somehow do that?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

温柔嚣张 2024-12-28 19:33:17

当您将 PictureBox 控件放入 List 容器中时,无法访问它们的 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;
        }
    }
}

The reason that you can't access the Image property of your PictureBox controls when you place them in a List<Control> container is because the base type of the list (Control) doesn't have an Image property.

The property didn't disappear, though. You just have to cast the object from a Control to a more derived class, PictureBox. Then you can call whatever methods or access whatever properties you want. For example:

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;
        }
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文