Windows Store App - c# - TextBlock检查文本是否被修剪

本文关键字:是否 文本 修剪 检查 TextBlock Store App Windows | 更新日期: 2023-09-27 18:12:20

TextBlock类中,有一个属性用于设置当文本超出控件的边界时控件的TextTrimming行为。

然而,我似乎找不到一个属性,可以通知我的应用程序,如果TextBlock已被修剪或没有。

我的问题是,我有一个固定大小的TextBlock,可以有文本超过大小。当发生这种情况时,我想动态调整字体大小以适应文本块。

你知道怎么做吗?

伪代码
// Function added to TextBlock as SizeChanged event handler. 
private void textBlock_SizeChanged(object sender, SizeChangedEventArgs e)
{
    TextBlock textBlock = sender as TextBlock;
    if(textBlock.IsTrimmed && textBlock.FontSize > 10) // NOTE: IsTrimmed Property does not exist.
    {
        textBlock.FontSize -= 10;
    }
}
然后UI线程将递归地收缩文本,直到它适合TextBlock

Windows Store App - c# - TextBlock检查文本是否被修剪

这是一个有效的解决方案。

    private void textBlock_SizeChanged(object sender, SizeChangedEventArgs e)
    {
        TextBlock tb = sender as TextBlock;
        if (tb != null)
        {
            Grid parent = tb.Parent as Grid;
            if(parent != null)
            {
                if(parent.ActualWidth < tb.ActualWidth)
                {
                    tb.FontSize -= 10;
                }
            }
        }
    }

虽然效率不高。如果有一种算法可以用来确定字体大小、字符串长度和像素宽度,那么它就可以得到改进。