You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

WPF Label文本行尾截断无法换行?已找到有效解决方案

WPF Label文本无法自动换行的问题与解决方法

我有一个WPF UserControl,内部包含一个4列1行的Grid控件,第二列放置了一个Label控件。但Label的文本在行尾被截断,无法自动换行,尝试通过Label的Resources设置TextBlock的TextWrapping为Wrap,但该方案并未生效。

初始代码

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="auto"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="auto"/>
        <ColumnDefinition Width="auto"/>
    </Grid.ColumnDefinitions>

    <!-- 仅保留Label代码以简化示例 -->
    <Label Grid.Column="1"
           VerticalAlignment="Center"
           Margin="5"
           Content="{Binding Path=Text}"
           Foreground="{Binding Path=ForegroundColor}">
        <Label.Resources>
            <Style TargetType="TextBlock">
                <Setter Property="TextWrapping" Value="Wrap" />
            </Style>
        </Label.Resources>
    </Label>
</Grid>

解决方法

通过调整Label的布局属性,并在Label内部直接嵌套TextBlock控件设置TextWrapping="Wrap",问题已完美解决:

<Label Grid.Column="1"
       VerticalAlignment="Center"
       VerticalContentAlignment="Center"
       HorizontalContentAlignment="Stretch"
       HorizontalAlignment="Stretch"
       Height="Auto"
       Margin="5"
       Foreground="{Binding Path=ForegroundColor}">
    <TextBlock Text="{Binding Path=Text}" TextWrapping="Wrap"/>
</Label>

说明

原方案失效原因在于:Label内部默认的ContentPresenter对TextBlock样式的继承存在限制,或Label的默认布局未让内容区域充分利用Grid列的可用空间。直接嵌套TextBlock并显式设置换行属性,同时将Label的HorizontalAlignment和HorizontalContentAlignment设为Stretch,确保TextBlock能获取足够的宽度进行自动换行。

内容的提问来源于stack exchange,提问作者Willy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.26 02:18:20