您可以通过首先检索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);
}
}
}
}
这是我刚刚编写的一个小测试工具的直接摘录 - 第一种方法是按钮单击处理程序,只是为了便于实验。
它使用VisualTreeHelper
来获取渲染Drawing
的TextBlock
- 只有当事物已经被渲染时才会起作用。然后该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);
}
}
}
}