WPF richTextBox问题

如果一行文本被包装到另一行,我如何以编程方式确定字符串中断点的位置。

示例:输入字符串=“这是对包装的文本行的测试”。

Based on the width of the richTextBox it could display: This is a test of a wrapped line of text. 

我需要确定的是被包裹的单词行中的偏移量。 在上面的例子中,单词“文本”。

当我从richTextBox中提取Xaml时,我将原始文本解包。

谢谢,

鲍勃克林格

我发现的技巧使用TextPointer类及其GetCharacterRec方法。

RichTextBox包含FlowDocument。 流文档中的文本包含在Run对象中(简化的一点,但它可以工作)。 代码在第一次运行的开始处找到TextPointer。 然后它获得第一个字符的边界矩形。 接下来,代码一次向前走一个字符,获取一个新的边界矩形并检查新矩形的底部是否与原始矩形不同。 如果底部不同,那么我们就在新的一条线上。 然后TextPointer可以在中断之前或之后获取文本。

 public partial class Window1 : Window { public Window1() { InitializeComponent(); } private void inspect(object sender, RoutedEventArgs e) { TextPointer pointer = FindRun(inBox.Document); string textAfterBreak = FindBreak(pointer); outBox.Text = textAfterBreak; } private string FindBreak(TextPointer pointer) { Rect rectAtStart = pointer.GetCharacterRect(LogicalDirection.Forward); pointer = pointer.GetNextInsertionPosition(LogicalDirection.Forward); Rect currentRect = pointer.GetCharacterRect(LogicalDirection.Forward); while (currentRect.Bottom == rectAtStart.Bottom) { pointer = pointer.GetNextInsertionPosition(LogicalDirection.Forward); currentRect = pointer.GetCharacterRect(LogicalDirection.Forward); } string textBeforeBreak = pointer.GetTextInRun(LogicalDirection.Backward); string textAfterBreak = pointer.GetTextInRun(LogicalDirection.Forward); return textAfterBreak; } private TextPointer FindRun(FlowDocument document) { TextPointer position = document.ContentStart; while (position != null) { if (position.Parent is Run) break; position = position.GetNextContextPosition(LogicalDirection.Forward); } return position; } }              

http://msdn.microsoft.com/en-us/library/system.windows.documents.textpointer.getlinestartposition.aspx

 TextPointer startOfFirstLine = richTextBox.Document.ContentStart; TextPointer startOfNextLine = startOfFirstLine.GetLineStartPosition(1); if(startOfNextLine != null) { // At this point what you do with the TextPointer depends on what you define as the position of text. // If you want to find out how many characters are on the first line ... int firstLineCharacterCount = new TextRange(startOfFirstLine, startOfNextLine).Text.Length; } 

startOfFirstLine.GetLineStartPosition(1)返回null