0

我想扩展一个面板,我想向这个类添加一些控件。但是我不知道把代码放在哪里,如果我把它放在构造函数中,它就不起作用了。让我们看看示例代码:

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

我认为是因为图像是在构造函数运行后设置的。但是我不知道哪个事件适合放这个方法。有人请帮助我,谢谢

4

1 回答 1

0

您的 image 属性不做任何事情。尝试这个:

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();
        }
    }
}
于 2013-04-20T17:30:43.307 回答