从TextBlock中获取显示的文本

Fre*_*lad 23 wpf text textblock texttrimming

我有一个像这样定义的简单TextBlock

<StackPanel>
    <Border Width="106"
            Height="25"
            Margin="6"
            BorderBrush="Black"
            BorderThickness="1"
            HorizontalAlignment="Left">
        <TextBlock Name="myTextBlock"
                   TextTrimming="CharacterEllipsis"
                   Text="TextBlock: Displayed text"/>
    </Border>
</StackPanel>
Run Code Online (Sandbox Code Playgroud)

哪个输出像这样

替代文字

这会让我"TextBlock:显示文字"

string text = myTextBlock.Text;
Run Code Online (Sandbox Code Playgroud)

但有没有办法获得实际显示在屏幕上的文字?
含义"TextBlock:显示......"

谢谢

Ian*_*ths 17

您可以通过首先检索Drawing表示TextBlock可视树中外观的对象,然后遍历查找GlyphRunDrawing项目 - 这些将包含屏幕上的实际呈现文本.这是一个非常粗略和准备好的实现:

private void button1_Click(object sender, RoutedEventArgs e)
{
    Drawing textBlockDrawing = VisualTreeHelper.GetDrawing(myTextBlock);
    var sb = new StringBuilder();
    WalkDrawingForText(sb, textBlockDrawing);

    Debug.WriteLine(sb.ToString());
}

private static void WalkDrawingForText(StringBuilder sb, Drawing d)
{
    var glyphs = d as GlyphRunDrawing;
    if (glyphs != null)
    {
        sb.Append(glyphs.GlyphRun.Characters.ToArray());
    }
    else
    {
        var g = d as DrawingGroup;
        if (g != null)
        {
            foreach (Drawing child in g.Children)
            {
                WalkDrawingForText(sb, child);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这是我刚刚编写的一个小测试工具的直接摘录 - 第一个方法是一个按钮点击处理程序,只是为了便于实验.

它使用VisualTreeHelper得到渲染到DrawingTextBlock-如果事情已经被渲染的方式是将只工作.然后该WalkDrawingForText方法执行实际工作 - 它只是遍历Drawing树寻找文本.

这不是非常聪明 - 它假设GlyphRunDrawing对象按照您想要的顺序出现.对于你的特定例子,我们得到一个GlyphRunDrawing包含截断的文本,然后是第二个包含省略号的文本.(顺便说一句,它只是一个unicode字符 - 代码点2026,如果这个编辑器允许我粘贴unicode字符,那就是"......".这不是三个独立的时期.)

如果你想让它更健壮,你需要计算出所有这些GlyphRunDrawing对象的位置,并对它们进行排序,以便按它们出现的顺序处理它们,而不是仅仅希望WPF碰巧产生它们.那个命令.

更新以添加:

以下是位置感知示例的外观草图.虽然这有点狭隘 - 它假设从左到右阅读文本.对于国际化解决方案,您需要更复杂的东西.

private string GetTextFromVisual(Visual v)
{
    Drawing textBlockDrawing = VisualTreeHelper.GetDrawing(v);
    var glyphs = new List<PositionedGlyphs>();

    WalkDrawingForGlyphRuns(glyphs, Transform.Identity, textBlockDrawing);

    // Round vertical position, to provide some tolerance for rounding errors
    // in position calculation. Not totally robust - would be better to
    // identify lines, but that would complicate the example...
    var glyphsOrderedByPosition = from glyph in glyphs
                                    let roundedBaselineY = Math.Round(glyph.Position.Y, 1)
                                    orderby roundedBaselineY ascending, glyph.Position.X ascending
                                    select new string(glyph.Glyphs.GlyphRun.Characters.ToArray());

    return string.Concat(glyphsOrderedByPosition);
}

[DebuggerDisplay("{Position}")]
public struct PositionedGlyphs
{
    public PositionedGlyphs(Point position, GlyphRunDrawing grd)
    {
        this.Position = position;
        this.Glyphs = grd;
    }
    public readonly Point Position;
    public readonly GlyphRunDrawing Glyphs;
}

private static void WalkDrawingForGlyphRuns(List<PositionedGlyphs> glyphList, Transform tx, Drawing d)
{
    var glyphs = d as GlyphRunDrawing;
    if (glyphs != null)
    {
        var textOrigin = glyphs.GlyphRun.BaselineOrigin;
        Point glyphPosition = tx.Transform(textOrigin);
        glyphList.Add(new PositionedGlyphs(glyphPosition, glyphs));
    }
    else
    {
        var g = d as DrawingGroup;
        if (g != null)
        {
            // Drawing groups are allowed to transform their children, so we need to
            // keep a running accumulated transform for where we are in the tree.
            Matrix current = tx.Value;
            if (g.Transform != null)
            {
                // Note, Matrix is a struct, so this modifies our local copy without
                // affecting the one in the 'tx' Transforms.
                current.Append(g.Transform.Value);
            }
            var accumulatedTransform = new MatrixTransform(current);
            foreach (Drawing child in g.Children)
            {
                WalkDrawingForGlyphRuns(glyphList, accumulatedTransform, child);
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)


Ste*_*bob 10

在我的Reflector周围扎根一段时间后,我发现了以下内容:

System.Windows.Media.TextFormatting.TextCollapsedRange 
Run Code Online (Sandbox Code Playgroud)

Length属性包含未显示的字符数(位于文本行的折叠/隐藏部分).知道了这个值,只需要减法即可获得显示的字符.

无法从TextBlock对象直接访问此属性.看起来它是WPF用来在屏幕上实际绘制文本的代码的一部分.

实际上,为TextBlock中的文本行实际获取此属性的值可能会非常麻烦.