我想扩展一个面板,我想为这个类添加一些控件。但我不知道在哪里放置代码,如果我把它放在构造函数中,它将无法正常工作。让我们看一下示例代码:
class ExPanel : Panel {
public Image image {
get;
set;
}
public ExPanel() {
// if I put the addPic method here, the picture will not be showed
}
private void addPic() {
PictureBox pic = new PictureBox();
pic.Top = 10; pic.Left = 10;
pic.Width = 100;
pic.Height = 100;
if (this.image != null) pic.Image = this.image;
this.Controls.Add(pic);
}
}
我认为是因为图像是在构造函数运行后设置的。但我不知道哪种事件适合放这种方法。 有人请帮助我,谢谢
答案 0 :(得分:0)
您的图片属性不执行任何操作。试试这个:
using System.Drawing;
using System.Windows.Forms;
public class ExPanel : Panel
{
PictureBox pic = new PictureBox();
public Image image
{
get { return pic.Image; }
set { pic.Image = value; }
}
public ExPanel()
{
addPic();
}
private void addPic()
{
pic.Top = 10; pic.Left = 10;
pic.Width = 100;
pic.Height = 100;
pic.BackColor = Color.Blue;
if (this.image != null) pic.Image = this.image;
this.Controls.Add(pic);
}
}
用法:
using System;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
var foo = new ExPanel();
Controls.Add(foo);
foo.image = System.Drawing.Image.FromFile(@"C:\foo.jpg");
foo.Refresh();
}
}
}