Bob*_*ger 6 c# wpf richtextbox
如果一行文本被包装到另一行,我如何以编程方式确定字符串中断点的位置.
示例:输入字符串="这是对包装的文本行的测试".
Based on the width of the richTextBox it could display:
This is a test of a wrapped line of
text.
Run Code Online (Sandbox Code Playgroud)
我需要确定的是被包裹的单词行中的偏移量.在上面的例子中,单词"文本".
当我从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;
}
}
<Window x:Class="LineBreaker.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Window1" Height="300" Width="300">
<Grid>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<RichTextBox Grid.Row="0" Name="inBox">
</RichTextBox>
<Button Grid.Row="1" Click="inspect">Find Break</Button>
<TextBox Name="outBox" Grid.Row="2"/>
</Grid>
</Window>
Run Code Online (Sandbox Code Playgroud)