如何实现自定义控件的AutoSize属性?

min*_*ina 5 .net c# custom-controls autosize winforms

我想在自定义控件(而不是用户控件)中实现AutoSize属性,以使其行为类似于在设计模式下实现AutoSize(ala CheckBox)的其他标准.NET WinForms控件。

我已经设置了属性,但是控件在设计模式下的行为方式困扰着我。它仍然可以调整大小,这没有意义,因为视觉调整大小没有体现在我实现的AutoSize和Size属性中。

当AutoSize为true时,标准.NET控件不允许在设计模式下调整大小(甚至显示调整大小的句柄)。我希望我的控件以相同的方式运行。

编辑:我可以使用SetBoundsCore()重写来工作,但是当AutoSize设置为true时,它在视觉上没有限制调整大小,它具有相同的效果;该功能是等效的,但感觉不自然。

protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified)
{
    if (!this.auto_size)
        this.size = new Size(width, height);
    base.SetBoundsCore(x, y, this.size.Width, this.size.Height, specified);
}
Run Code Online (Sandbox Code Playgroud)

关于以标准方式执行此操作的任何想法?

小智 5

这是让您控制AutoSize的食谱。

创建方法GetAutoSize()来根据您的特定实现计算所需的控件大小。可能是它包含的文本的大小,或者是当前宽度的控件的总高度,无论如何。

创建一个ResizeForAutoSize()方法,以强制控件在状态更改后自行调整大小。例如,如果控件是根据其包含的文本调整大小的,则更改文本应调整控件的大小。文本更改时只需调用此方法。

重写GetPreferredSize()通知想要知道的人(例如FlowLayoutPanel)是我们的首选大小。

覆盖SetBoundsCore()以强制执行大小调整规则,就像无法调整AutoSize标签大小一样。

在此处查看示例。

/// <summary>
/// Method that forces the control to resize itself when in AutoSize following
/// a change in its state that affect the size.
/// </summary>
private void ResizeForAutoSize()
{
    if( this.AutoSize )
        this.SetBoundsCore( this.Left, this.Top, this.Width, this.Height,
                    BoundsSpecified.Size );
}

/// <summary>
/// Calculate the required size of the control if in AutoSize.
/// </summary>
/// <returns>Size.</returns>
private Size GetAutoSize()
{
    //  Do your specific calculation here...
    Size size = new Size( 100, 20 );

    return size;
}

/// <summary>
/// Retrieves the size of a rectangular area into which
/// a control can be fitted.
/// </summary>
public override Size GetPreferredSize( Size proposedSize )
{
    return GetAutoSize();
}

/// <summary>
/// Performs the work of setting the specified bounds of this control.
/// </summary>
protected override void SetBoundsCore( int x, int y, int width, int height,
        BoundsSpecified specified )
{
    //  Only when the size is affected...
    if( this.AutoSize && ( specified & BoundsSpecified.Size ) != 0 )
    {
        Size size = GetAutoSize();

        width   = size.Width;
        height  = size.Height;
    }

    base.SetBoundsCore( x, y, width, height, specified );
}
Run Code Online (Sandbox Code Playgroud)


Dav*_*son 0

在控件的构造函数中,调用 SetAutoSizeMode(AutoSizeMode.GrowAndShrink)。