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; } }
https://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
上述就是C#学习教程:WPF richTextBox问题分享的全部内容,如果对大家有所用处且需要了解更多关于C#学习教程,希望大家多多关注—计算机技术网(www.ctvol.com)!
本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。
ctvol管理联系方式QQ:251552304
本文章地址:https://www.ctvol.com/cdevelopment/984599.html