How can I wrap text in a label using WPF?

2019-01-10 18:22发布

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.

10条回答
叛逆
2楼-- · 2019-01-10 18:34

try use this

lblresult.Content = lblresult.Content + "prime are :" + j + "\n";
查看更多
老娘就宠你
3楼-- · 2019-01-10 18:35
 <Label x:Name="datetimeofmsg" 
           HorizontalAlignment="Left" Margin="4.286,55,0,0" 
           VerticalAlignment="Top" Background="{x:Null}" 
           FontWeight="Bold" Width="61.714" Height="20" Foreground="White">
        <Label.Content>
            <AccessText TextWrapping="Wrap"/>
        </Label.Content>
    </Label>
查看更多
别忘想泡老子
4楼-- · 2019-01-10 18:37

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 e.g. 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.

查看更多
Melony?
5楼-- · 2019-01-10 18:39

I used the following code.

    <Label>
        <Label.Content>
            <AccessText TextWrapping="Wrap" Text="xxxxx"/>
        </Label.Content>
    </Label>
查看更多
登录 后发表回答