C# 初始控件不显示

C# 初始控件不显示,c#,.net,controls,C#,.net,Controls,我想扩展一个面板,并向这个类添加一些控件。但是我不知道把代码放在哪里,如果我把它放在构造函数中,它就不会工作。让我们看看示例代码: class ExPanel : Panel { public Image image { get; set; } public ExPanel() { // if I put the addPic method here, the picture will not be showed

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

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);
    }
}
我认为这是因为映像是在构造函数运行之后设置的。但我不知道哪个事件适合使用这种方法。
有人请帮帮我,谢谢

您的图像属性没有任何作用。试试这个:

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

尝试将此调用添加到表单的
InitializeComponent()
方法中。您可以说,“图片将不会显示”。这是因为您刚刚创建了一个新的PictureBox,我没有看到任何代码将图片放入其中。@raven:我的意思是不会显示PictureBox,我将背景颜色设置为蓝色。。。然后设置
pic.Visible=true
@HuorSwords:你的方法行不通,我只是试了一下。请再看一下样品。我刚刚编辑了它。在我编辑的示例中,我删除了行
pic.BackColor=Color.Blue。它可以与颜色一起工作,但图像是difference@SmartGoat:图像属性没有任何作用。请参见上面的编辑。如果我在设计时通过属性添加图像。这是行不通的。在属性中更改图像时调用的事件。这就是我发现的。