无法多次显示相同的PictureBox

时间:2017-01-03 01:37:44

标签: c# winforms picturebox

        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上呈现以下输出(请注意图标):

two icons

但是,如果我将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);

我只获得一个图标输出。

one icon

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

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

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

2 个答案:

答案 0 :(得分:1)

当你设置another = aCollection[289]时,你引用的是与设置condition =时相同的对象。因此,当您更新其他人的位置时,您正在更改aCollection[289]的位置(以及condition

您需要创建2个单独的对象实例才能添加2个图片框。可能最好使用扩展方法来执行对象的深层复制,然后将它们添加到Controls。添加此课程:

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

答案 1 :(得分:0)

同一个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));