c#当子pictureBox更改图像时调整父控件的大小

c#当子pictureBox更改图像时调整父控件的大小,c#,user-controls,picturebox,autoresize,C#,User Controls,Picturebox,Autoresize,我有一个UserControl,它包含一个PictureBox和一个标签。控件在不同事件(例如onMouseEnter、onmouseeve)的PictureBox中加载三个不同的图像。由于图像可以有不同的大小,我需要调整pictureBox和 控件本身。下面提供了控件的OnPaint事件,但这不起作用 protected override void OnPaint(PaintEventArgs pe) { if (pictureBox.Image != nul

我有一个UserControl,它包含一个PictureBox和一个标签。控件在不同事件(例如onMouseEnter、onmouseeve)的PictureBox中加载三个不同的图像。由于图像可以有不同的大小,我需要调整pictureBox和 控件本身。下面提供了控件的OnPaint事件,但这不起作用

    protected override void OnPaint(PaintEventArgs pe)
    {

        if (pictureBox.Image != null)
        {
            this.Width = this.pictureBox.Image.Size.Width;
            this.Height = this.pictureBox.Image.Size.Height;
            CutRoundedRectangle2(pictureBox, cornerRadius);
        }
        else
        {
            Bitmap DrawArea = new Bitmap(pictureBox.Size.Width, pictureBox.Size.Height);
            Graphics g = Graphics.FromImage(DrawArea);
            Pen mypen = new Pen(Color.Black);
            pictureBox.Image = DrawArea;
            System.Drawing.Pen pen = new Pen(new SolidBrush(this.ForeColor));
            g.DrawRectangle(pen, 0, 0, this.Width-1, this.Height-1);
            g.Dispose();
        }
        this.labelText.ocation = new Point((this.pictureBox.Width - this.labelText.Width) / 2,
                                            (this.pictureBox.Height - this.labelText.Height) / 2);
        base.OnPaint(pe);
    }
pictureBox SizeMode在控件的构造函数中设置:

this.pictureBox.SizeMode = PictureBoxSizeMode.AutoSize;

上次我使用WinForms是很久以前的事了,但是…

我的第一个想法是:您是否尝试过将父控件的
AutoSize
属性的值设置为“true”和
AutoSizeMode
设置为
growthandshrink
,并在将新图像加载到图片框时调用父控件的
Refresh()
方法?

@Alexey,pictureBox resize事件有帮助

    private void pictureBox_Resize(object sender, EventArgs e)
    {
        this.Width = this.pictureBox.Image.Size.Width;
        this.Height = this.pictureBox.Image.Size.Height;
    }