One of the few annoyances I occasionally get with C# is the lack
of a word wrap facility for the standard Label
control.
Instead, if the AutoSize
property is set to true
, the label
will just get wider and wider. In order to wrap it, you have to
disable auto resize then manually ensure the height of the label
is sufficient.
The base Control
class has method named GetPreferredSize
which is overridden by derived classes. This method will
calculate the size of a control based on a suggested value. By
calling this method and overriding the OnTextChanged
and
OnResize
methods, we can very easily create a custom label
that automatically wraps and resizes itself vertically to fit
its contents.
Paste in the following code into a new Component to have a read-to-run wrappable label.
So, what is the code doing? It's very straightforward.
In the constructor, we are disabling the built in auto resize functionality, otherwise you won't be able to resize the control in the designer.
Next, we want to override the OnTextChanged
and OnResize
methods to call our new resize functionality. By overriding
these, we can ensure that the control will correctly resize as
required.
Now to implement the actual resize functionality. The
FitToContents
method calls the label's GetPreferredSize
method, passing in the width of the control. This method returns
a Size
structure which is large enough to hold the entire
contents of the control. We take the Height of this (but not the
width) and apply it to the label to make it resize vertically.
When calling GetPreferredSize
, the size we passed in only
had the width specified, which will be the maximum width
returning. As we passed in zero for the height, the method
defines its own maximum height.
Finally, you'll note that we have overridden the AutoSize
property itself and added a number of attributes to it to make
sure it doesn't appear in any property or code windows, and to
prevent its value from being serialized.
Update History
- 2010-05-21 - First published
- 2020-11-21 - Updated formatting
Like what you're reading? Perhaps you like to buy us a coffee?
# Aaron
# Richard Moss
# Jim
# Exorsus
# Peter