[英]Implementing AutoSize in a custom UserControl
I have a custom UserControl which draws text and graphics using GDI+. 我有一个自定义UserControl,它使用GDI +绘制文本和图形。 Normally I dock it using DockStyle.Bottom within another control.
通常我在另一个控件中使用DockStyle.Bottom将其停靠。
The size of this control is determined by a custom layout using Graphics.MeasureString(). 该控件的大小由使用Graphics.MeasureString()的自定义布局确定。 Therefore, it needs to recalculate the height everytime the width changes, which is changed when the parent width changes.
因此,每次宽度改变时都需要重新计算高度,而父宽度改变时,高度也会改变。
Currently I am setting this control's height in its OnSizeChanged event. 目前,我正在其OnSizeChanged事件中设置此控件的高度。 However I am noticing some bugs with this.
但是,我注意到与此有关的一些错误。 Sometimes when I resize the parent, the control is not touching the bottom of the parent, even though it is set to DockStyle.Bottom.
有时,当我调整父对象的大小时,即使将其设置为DockStyle.Bottom,该控件也不会触及父对象的底部。 I used Spy++ to analyze the control bounds and there is simply some empty space between the control and the edge of the parent by about 20 pixels.
我使用Spy ++来分析控件边界,并且控件和父对象的边缘之间只有大约20个像素的空白。
I want to implement a proper AutoSize in this UserControl assuming a Top or Bottom DockStyle. 我想在此UserControl中实现适当的AutoSize(假定顶部或底部DockStyle)。
The DefaultLayout engine for WindowsForms has quite a bit logic in there for laying out docked controls. WindowsForms的DefaultLayout引擎具有相当多的逻辑,可用于布置停靠的控件。 I would recommend a decompiler (dotPeek, Reflector, etc.) and decompile the DefaultLayout class.
我建议使用反编译器(dotPeek,Reflector等)并反编译DefaultLayout类。
There is a lot interaction between the control itself, its children, whether it overrides GetPreferredSize etc. etc. 控件本身,其子级,是否覆盖GetPreferredSize等之间存在很多交互。
Perhaps when you understand the context under which your GetPreferredSize is called, you'll get a better idea of how to implement it. 也许当您了解调用GetPreferredSize的上下文时,会更好地了解如何实现它。
In terms of sample implementations, again, what better than the Windows controls themselves? 同样,在示例实现方面,还有什么比Windows控件更好的控件? Decompile a few.
反编译一些。 Here'as an example from ToolStripItem
这是来自ToolStripItem的示例
public virtual Size GetPreferredSize(Size constrainingSize)
{
constrainingSize = LayoutUtils.ConvertZeroToUnbounded(constrainingSize);
return this.InternalLayout.GetPreferredSize(constrainingSize - this.Padding.Size) + this.Padding.Size;
}
Good luck! 祝好运!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.