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

UWP应用中如何判断TextBlock控件内的文本内容是否溢出?

UWP TextBlock 文本溢出判断实现方案

UWP 的 TextBlock 没有专门的溢出触发事件,但可以通过以下两种成熟方案实现溢出判断:

方案1:使用内置 IsTextTrimmed 属性(推荐)

这个属性是 Windows 10 1607 版本(SDK 版本 14393)后新增的原生属性,使用成本最低。

使用步骤:

  1. 给你的 TextBlock 配置 TextTrimming 并添加命名:
<TextBlock 
    x:Name="AboutTitleTextBlock"
    Margin="{StaticResource SmallTopMargin}"
    Style="{StaticResource SubtitleTextStyle}"
    Text="{x:Static properties:Resources.SettingsPageAboutTitle}"
    TextTrimming="CharacterEllipsis" />
  1. 直接在后台代码读取属性值即可:
    bool isOverflow = AboutTitleTextBlock.IsTextTrimmed;
    返回 true 代表文本已超出控件区域被裁剪,false 代表未溢出。

方案2:手动计算文本尺寸(兼容低版本/无裁剪场景)

如果你的项目需要兼容低于 14393 的系统版本,或者没有开启文本裁剪也要判断是否溢出,可以通过计算文本实际渲染尺寸和控件可用尺寸的差值实现。

工具方法示例:

using System.Globalization;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Media;

public static bool CheckTextOverflow(TextBlock textBlock)
{
    if (textBlock == null || string.IsNullOrEmpty(textBlock.Text))
        return false;

    FormattedText formattedText = new FormattedText(
        textBlock.Text,
        CultureInfo.CurrentCulture,
        textBlock.FlowDirection,
        new Typeface(textBlock.FontFamily, textBlock.FontStyle, textBlock.FontWeight, textBlock.FontStretch),
        textBlock.FontSize,
        textBlock.Foreground
    );

    // 适配自动换行场景
    if (textBlock.TextWrapping != TextWrapping.NoWrap)
    {
        formattedText.MaxTextWidth = textBlock.ActualWidth;
    }

    // 对比文本实际需要的尺寸和控件可用尺寸
    return formattedText.Width > textBlock.ActualWidth || formattedText.Height > textBlock.ActualHeight;
}

注意事项:

  • 不要在页面构造函数中调用该方法,此时控件还未完成渲染,ActualWidth/ActualHeight 会返回 0,建议在 TextBlock 的 Loaded 事件、SizeChanged 事件或者 Text 属性变更时调用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 21:45:04