简体   繁体   中英

Implementing AutoSize in a custom UserControl

I have a custom UserControl which draws text and graphics using GDI+. Normally I dock it using DockStyle.Bottom within another control.

The size of this control is determined by a custom layout using 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. 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. 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.

I want to implement a proper AutoSize in this UserControl assuming a Top or Bottom DockStyle.

The DefaultLayout engine for WindowsForms has quite a bit logic in there for laying out docked controls. I would recommend a decompiler (dotPeek, Reflector, etc.) and decompile the DefaultLayout class.

There is a lot interaction between the control itself, its children, whether it overrides GetPreferredSize etc. etc.

Perhaps when you understand the context under which your GetPreferredSize is called, you'll get a better idea of how to implement it.

In terms of sample implementations, again, what better than the Windows controls themselves? Decompile a few. Here'as an example from ToolStripItem

 public virtual Size GetPreferredSize(Size constrainingSize)
    {
      constrainingSize = LayoutUtils.ConvertZeroToUnbounded(constrainingSize);
      return this.InternalLayout.GetPreferredSize(constrainingSize - this.Padding.Size) + this.Padding.Size;
    }

Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM