2012-03-25 185 views
4

我想在自定义控件中实现一个AutoSize属性(而不是用户控件),其行为与在设计模式下实现AutoSize(ala CheckBox)的其他标准.NET WinForms控件一样。如何实现自定义控件的AutoSize属性?

我有属性设置,但它是控制在设计模式下的行为方式使我感到困惑。 它仍然可以调整大小,这是没有意义的,因为视觉大小不会反映在我已经实现的AutoSize和Size属性中。

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

编辑:我有工作使用SetBoundsCore()重写,但它不会在视觉上限制调整大小时自动调整大小设置为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); 
} 

这样做的标准方式的任何想法?

+0

你使用的是什么UI库?的WinForms? WPF? ASP.NET?还有别的吗? – svick 2012-03-25 00:55:30

+0

Winforms,编辑在=] – mina 2012-03-25 01:11:31

+0

你尝试添加sizechanged事件,并把你的调整大小逻辑? – Oztaco 2012-03-25 04:14:04

回答

0

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

0

重写SizeFromClientSize()方法。在这种方法中,您必须计算所需控件的大小并将其返回。

3

这里是我的食谱,有你的控制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); 
}