How can I wrap text in a label using WPF?

I have a TextBox and a Label. After clicking a button, I execute the following code:

 label1.Content = textbox1.Text; 

My question is, how do I enable text wrapping of the label? There may be too much text to display on one line, and I want it to automatically wrap to multiple lines if that is the case.


The Label control doesn't directly support text wrapping in WPF. You should use a TextBlock instead. (Of course, you can place the TextBlock inside of a Label control, if you wish.)

Sample code:

<TextBlock TextWrapping="WrapWithOverflow">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec adipiscing
    nulla quis libero egestas lobortis. Duis blandit imperdiet ornare. Nulla
    ac arcu ut purus placerat congue. Integer pretium fermentum gravida.
</TextBlock>

Often you cannot replace a Label with a TextBlock as you want to the use the Target property (which sets focus to the targeted control when using the keyboard eg ALT+C in the sample code below), as that's all a Label really offers over a TextBlock .

However, a Label uses a TextBlock to render text (if a string is placed in the Content property, which it typically is); therefore, you can add a style for TextBlock inside the Label like so:

<Label              
    Content="_Content Text:"
    Target="{Binding ElementName=MyTargetControl}">
    <Label.Resources>
        <Style TargetType="TextBlock">
            <Setter Property="TextWrapping" Value="Wrap" />
        </Style>
    </Label.Resources>
 </Label>
 <CheckBox x:Name = "MyTargetControl" />

This way you get to keep the functionality of a Label whilst also being able to wrap the text.


我使用了下面的代码。

    <Label>
        <Label.Content>
            <AccessText TextWrapping="Wrap" Text="xxxxx"/>
        </Label.Content>
    </Label>
链接地址: http://www.djcxy.com/p/50516.html

上一篇: 丰富的WPF格式文本显示选项

下一篇: 如何使用WPF将文本包装到标签中?