我正在初始化我的 Richtextbox,
void InitRTBFlowDocument()
{
Style noSpaceStyle = new Style(typeof(Paragraph));
noSpaceStyle.Setters.Add(new Setter(Paragraph.MarginProperty, new Thickness(0)));
rtbTextEditor.Resources.Add(typeof(Paragraph), noSpaceStyle);
}
我想获取 Richtext 框选择字的行号和列号。我编写的代码如下,第一次正确返回。
void rtbTextEditor_SelectionChanged(object sender, RoutedEventArgs e)
{
//Get the richtext box selected text
Init.RTBSelectionText = rtbTextEditor.Selection.Text.Trim();
Init.SelectionText = rtbTextEditor.Selection.Text.Trim();
Init.isSelect = true;
if (Init.RTBSelectionText != string.Empty)
{
TextPointer tp = rtbTextEditor.Selection.Start.GetPositionAtOffset(-2, LogicalDirection.Forward);
if (tp != null)
GetStartingIndex();
}
Init.RTBContent = new TextRange(rtbTextEditor.Document.ContentStart, rtbTextEditor.Document.ContentEnd).Text;
}
void GetStartingIndex()
{
TextPointer tp1 = rtbTextEditor.Selection.Start.GetLineStartPosition(0);
TextPointer tp2 = rtbTextEditor.Selection.Start;
int SelectionColumnIndex = tp1.GetOffsetToPosition(tp2)-1;//column number
int someBigNumber = int.MaxValue;
int lineMoved;
rtbTextEditor.Selection.Start.GetLineStartPosition(-someBigNumber, out lineMoved); //Line number
int SelectionRowIndex = -lineMoved;
Init.RTBTextPoint = new RTBTextPointer();
Init.RTBTextPoint.Row = SelectionRowIndex;
Init.RTBTextPoint.Column = SelectionColumnIndex;
}
清除并添加新内容后,位置返回错误数字,
public void DisplayContent(string content)
{
//Clear the rich text box
rtbTextEditor.Document.Blocks.Clear();
rtbTextEditor.Document.Blocks.Add(new Paragraph(new Run(content)));
}
上面的代码有什么问题吗?请帮助我提前谢谢!