不能多次显示同一个 PictureBox

Can't display the same PictureBox more than once

        Dictionary<int, PictureBox> aCollection;

        aCollection = new Dictionary<int, PictureBox>();

        aCollection.Add(333, new PictureBox
            {
                Name = "Alcoholism",
                Image = Resources.alcoholism,
                Size = new Size(22, 22),
                SizeMode = PictureBoxSizeMode.StretchImage
        });

        aCollection.Add(289, new PictureBox
        {
            Name = "Hypertension",
            Image = Resources.hypertension,
            Size = new Size(22, 22),
            SizeMode = PictureBoxSizeMode.StretchImage
        });

        PictureBox condition = aCollection[333]; //333 refers to alcoholism
        condition.Location = new Point(450, 155);
        displayForm.Controls.Add(condition);

        PictureBox another = aCollection[289]; //289 refers to hypertension
        another.Location = new Point(550, 155);
        displayForm.Controls.Add(another);

上面的代码在 Winform 上呈现以下输出(注意图标):

但是,如果我将两者 PictureBox 切换为使用相同的图标,并希望显示相同的图标 两次

        PictureBox condition = aCollection[289]; //Hypertension
        condition.Location = new Point(450, 155);
        displayForm.Controls.Add(condition);

        PictureBox another = aCollection[289]; //Hypertension
        another.Location = new Point(550, 155);
        displayForm.Controls.Add(another);

我只有一个图标输出。

有人可以告诉我哪里出错了吗?谢谢。

[编辑] - 以下代码也只生成一个图标

    PictureBox condition = aCollection[289];
    condition.Location = new Point(450, 155);
    displayForm.Controls.Add(condition);

    PictureBox another = condition;
    another.Location = new Point(550, 155);
    displayForm.Controls.Add(another);

同一个 PictureBox 控件不能同时位于多个位置,因此需要一个新的。

PictureBox newPictureBox(Image image, int X, int Y) {
    return new PictureBox() {
        Image = image,
        Size = new Size(22, 22),
        Location = new Point(X, Y),
        SizeMode = PictureBoxSizeMode.StretchImage
    };
}

然后是

displayForm.Controls.Add(newPictureBox(Resources.hypertension, 450, 155));
displayForm.Controls.Add(newPictureBox(Resources.hypertension, 550, 155));

当您设置 another = aCollection[289] 时,您引用的对象与为它设置条件 = 时引用的对象相同。因此,当您更新另一个位置时,您正在更改 aCollection[289](以及 condition

的位置

您需要创建 2 个单独的对象实例才能添加 2 个图片框。可能最好创建一个扩展方法来对对象进行深拷贝,然后将它们添加到控件中。添加这个 class:

public static class MyExtension
{
    public static PictureBox DeepCopy(this PictureBox pb)
    {
        return new PictureBox { Name = pb.Name, Image = pb.Image, Size = pb.Size, SizeMode = pb.SizeMode };
    }
}

然后添加图片框使用:

    PictureBox condition = aCollection[289].DeepCopy(); //289 refers to hypertension
    condition.Location = new Point(450, 155);
    this.Controls.Add(condition);

    PictureBox another = aCollection[289].DeepCopy(); //289 refers to hypertension
    another.Location = new Point(550, 155);
    this.Controls.Add(another);