Saturday, January 10, 2009

How to make the text of a CheckBox wrap across multiple lines

Just a quick one about how to make CheckBox text wrap across multiple lines while showing text accelerators correctly.

You might have noticed that a CheckBox doesn't have properties like TextWrapping and TextTrimming. This is because CheckBox derives from ContentControl and can therefore take any element as its content - it doesn't have to be a string like in the bad old WinForms days.

In order to add text wrapping, you could add a TextBlock to the Content of the CheckBox like this:
<CheckBox>
    <TextBlock TextWrapping="Wrap"
        Text="_This is a long piece of text attached to a checkbox."/>
</CheckBox>
There is a problem regarding accelerator keys here though. Look at the output from the last example:




...the accelerator isn't display correctly. TextBlocks don't support accelerator keys. In order to do this properly you should use an AccessText element to display your text:
<CheckBox>
    <AccessText TextWrapping="Wrap"
        Text="_This is a long piece of text attached to a checkbox."/>
</CheckBox>
This will ensure that the underscore is correctly displayed.



1 comments:

Bobby said...

Nice work! Thanks for the tip, was just what I was looking for.