我有一个 C# winform
,它显示来自相机的快照。该窗体有四个 PictureBox
控件,当拍摄图像时,它被放置在 pictureBox1
中,之前的图像被移动到 2、3 和 4。每个图片框下面是还有一个显示时间戳和订单号的标签(每个图像都有一个编号 1-4,该编号一直保留到它被撞掉,最新的图像采用该编号)。目前我正在这样做,如下所示。但是我觉得这是非常低效的,如果我决定添加按键事件来更改某些标签的背景色(以指示状态),以后会给我带来问题。
有谁知道更好的方法吗?
if (count > 4)
{
count = 0
}
count ++;
pictureBox4.image = pictureBox3.image;
pictureBox3.image = pictureBox2.image;
pictureBox2.image = pictureBox1.image;
pictureBox1.imagelocation = (@"http://192.168.X.X/image.cgi")
label4.Text =label3.text;
label3.text = label2.text;
label2.text = label1.text;
label1.text = count.ToString()+ " " + datetime.now();
最佳答案
我可以创建一个新的控件,很可能是一个面板,其中包含所有这些 UI 元素(图片框、标签等)。为您的 Control 创建一个构造函数,该构造函数采用图像的 URL。将图像加载到 PictureBox 中,并设置标签。
将所有这些逻辑封装在您的控件中。因此,当添加一个新控件时,您只需创建新控件,然后删除行中的最后一个控件,然后将剩余的 3 个控件的 .Left
属性移动到它们的新位置。
不要忘记实现 IDisposable
,并在移除控件时释放控件以释放显示图像的资源。
编辑
如果它不存在,您可以在每个内部控件(PictureBox 和 Label)中提供对顶部控件的引用,甚至通过传递 this
提供对顶部控件中的主窗体的引用作为构造函数中的参数,并在这些控件中设置私有(private)成员变量。这样,当有人单击 PictureBox 时,您可以上行到 this.Parent
并获取外部控件。您甚至可以引用您的主窗体(希望其中有一个面板可以容纳您的 4 个对象)。这可能是 this.Parent.Parent
在那里调用一个方法。 (我认为所有控件上已经有 Parent 的公共(public)属性,所以没关系。)
一些快速编码:
您有主 Form
(mainForm
)。里面有一个Panel
(picturePanel
)。 picturePanel
包含 4 个新的 Panel
,我们称之为 customPanel
。每个 customPanel
都有一个 PictureBox
(imageBox
) 和 Label (fileNameLabel
)。
您的 customPanel
构造函数如下所示:
public partial class CustomPanel : Panel {
private PictureBox _imageBox;
private Label _fileNameLabel;
public CustomPanel() {} // This is most likely tied into the code behind file. Sorry, It's been a while since I've done WinForms
public CustomPanel(string imageFileName, Panel parent) {
// Set the source for the PictureBox.
// Set the Text of the label.
_parent = parent;
}
}
通过 PictureBox 和 Label 继续这一行。然后在您的事件中,您可以让 PictureBox 在链上运行。找到picturePanel
。如果你真的想变得很花哨,你也可以从 Panel
派生它,只需添加一个公共(public)属性来处理 customPanel
发送消息的所有切换.
所以在你的 PictureBox 事件中,你可以有这样一行代码:
if (this.Parent.Parent is PicturePanel) {
((PicturePanel)this.Parent.Parent).RemovePicture(this.Parent);
}
关于c# - 发布设计代码来管理对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22660592/