Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Automatic line break in WPF label

Is it possible for a WPF Label to split itself automatically into several lines? In my following example, the text is cropped at the right.

<Window x:Class="..." xmlns="..." xmlns:x="..." Height="300" Width="300">
    <Grid>
        <Label>
            `_Twas brillig, and the slithy toves did gyre and gimble in the wabe:
            all mimsy were the borogoves, and the mome raths outgrabe.
        </Label>
    </Grid>
</Window>

Am I doing something wrong?

Taking other controls is unfortunately not a good option, since I need support of access keys.

Replacing the Label with a TextBlock (having TextWrapping="Wrap"), and adjusting its control template to recognize access keys would be perhaps a solution, but isn't it an overkill?

Edit: having a non-standard style for label will break skinning, so I would like to avoid it, if possible.

like image 203
Vlad Avatar asked Mar 19 '10 15:03

Vlad


People also ask

How do I wrap text in a label in WPF?

In WPF, the Label control does not support text wrapping. If you need a label that wraps contents across multiple lines, you can use a TextBlock control. Place a TextBlock control inside a Label and apply wrapping on TextBlock.

How to do line break in XAML?

XAML attributes of type String may contain any special characters, as long as those are referenced as hex-codes. For example, a simple line break ( \n ) would be represented as &#x0a; , for \r\n you'd use &#x0d;&#x0a; and so on.

How do I create a line break in TextBlock WPF?

Adding Line Breaks Sometimes you will want to insert a line break within a TextBlock. You can do this with a LineBreak inline, added as an XAML element within the text. A new line will be started at the position of this element.

How do you add a line in WPF?

To draw a line, create a Line element. Use its X1 and Y1 properties to set its start point; and use its X2 and Y2 properties to set its end point. Finally, set its Stroke and StrokeThickness because a line without a stroke is invisible. Setting the Fill element for a line has no effect, because a line has no interior.


1 Answers

Using both Label and TextBlock together seems to be the correct answer. There's a howto located here that demonstrates this exact issue.

Specifically, in their example, to get wrapping text and an access key:

<Label Width="200" HorizontalAlignment="Left"
       Target="{Binding ElementName=textBox1}">
  <AccessText TextWrapping="WrapWithOverflow">
    _Another long piece of text that requires text wrapping
    goes here.
  </AccessText>
</Label>
like image 53
Ben Von Handorf Avatar answered Oct 07 '22 16:10

Ben Von Handorf