Adding some much needed dock sizing for System.Windows.Forms.Label... (Whidbey, but probably works on V1.x)
I'm working on a control that allows you to add labels to a panel that allows scrolling. This is key for implementing anything that would otherwise require a list control to display data items. I'd rather just use the labels and a panel for my case because it is easier. I've started with the following.
- Panel control with AutoSize = false, AutoScroll = true
- Label controls with AutoSize = true, Dock = DockStyle.Top
Now, when I add the labels I set their client index to 0, so they dock moving downwards in the list. A simple ScrollIntoView on the newly added label makes sure it is visible. This process immediately had a problem. AutoSize only works in the horizontal direction. It doesn't allow me to create labels that say dock to the top of a control and then size vertically creating multiple lines for text as needed. Well, that is bogus. I added a simple override to the OnResize method that checks for a specific docking mode and then resize the control appropriately. I call it the DockSizableLabel.
public class DockSizableLable : Label {
protected override void OnResize( EventArgs e ) {
if ( this.Dock == DockStyle.Top || this.Dock == DockStyle.Bottom ) {
using ( Graphics gfx = this.CreateGraphics() ) {
SizeF size = gfx.MeasureString( this.Text, this.Font, this.ClientSize.Width );
this.ClientSize =
new Size(
this.ClientSize.Width,
(int) size.Height );
}
}
base.OnResize( e );
}
}
Haven't put a bunch of testing into it, but it appears to work quite well. You could probably do some extra process in adding Padding/Margin support or add some form of text-decorations, but I was simply looking for a quick fix. This code allows me to resize the window as needed and works quite fast even up to a few hundred labels in the queue. I'm sure I won't be able to scale to thousands of labels in the same panel, but I'm not after that type of support.