Phil Wright : Component Factory

Tuesday, July 12, 2005

.NET2, AutoSize

.NET Framework 2

Version 2 of the .NET Framework is a great improvement for Windows.Forms developers. Each time I investigate a new area I find some cool new feature that makes life so much easier than before.

Control.DisplayRect

My previous technical entry has already mentioned use of the DisplayRect property as a way of controlling the child space available for positioning children. This is a great feature and without this it would be a real pain to achieve the same effect.

Control.AutoSize

Now I have noticed another great addition that will save developers time. There is a new Control property called AutoSize that does exactly what it says. When defined it will automatically resize the control appropriately.

For instance, if you create a Button control instance then the control will size itself to fit the Text content. Now this might not sound very exciting, but in the past you had a real pain getting a control such as a Button to size properly.

For a start you would have to get the Font used by the Control and then measure the size of the Text for that Font. Then you need to add on a sensible spacing gap around the text and finally add the border allocation. Not rocket science but still a pain to have to write the code.

Header and Button

Knowing this great new property is available means I want my own controls to provide the same functionality. If a user can take advantage of AutoSize on a standard windows Button then they will, quite reasonably, expect my own controls to provide the same functionality.

As the image from a previous post show, I have completed the simple Header control for the library. I am now into the process of creating a Button control that reuses the same rendering process.

After a little investigation I worked out how to hook into the auto sizing process. It turns out to be really easy and I recommend that anyone else writing a custom control also adds the capability.

GetPreferredSize

All you need to do is override the virtual method called GetPreferredSize and return from it a Size instance the is the preferred size you would like your control to be. That's it. Just override that one method and your done.

This is so simple there is no excuse for not adding it to your own controls.

0 Comments:

Post a Comment

<< Home