我正在开发一个小型 WPF 应用程序,其中有多个选项卡。我在底部有一个状态栏;要求是显示光标的行号和列。因此,当用户更改光标位置时,行号和列必须自动更新。这是我添加 RichTextBox 的代码;计算行号和列的代码在 KeyDown 事件处理程序中,但永远不会调用此事件。我应该处理哪个事件来获取光标的行号和列?
private void AddTabitem(string filePath, mode fileMode)
{
if (fileMode == mode.openFile)
{
if (File.Exists(filePath))
{
RichTextBox mcRTB = new RichTextBox();
mcRTB.KeyDown += new KeyEventHandler(LineNumber);
//rest of the code goes here
}
}
}
mcRTB.KeyDown += new KeyEventHandler(LineNumber);
private void LineNumber(object sender, KeyEventArgs e)
{
TextPointer tp1 = rtbList[EditorTabcontrol.SelectedIndex].Selection.Start.GetLineStartPosition(0);
TextPointer tp2 = rtbList[EditorTabcontrol.SelectedIndex].Selection.Start;
int column = tp1.GetOffsetToPosition(tp2);
int someBigNumber = int.MaxValue;
int lineMoved, currentLineNumber;
rtbList[EditorTabcontrol.SelectedIndex].Selection.Start.GetLineStartPosition(-someBigNumber, out lineMoved);
currentLineNumber = -lineMoved;
string LineColumnLabel;
//LineColumnLabel.Content = "Line: " + currentLineNumber.ToString() + " Column: " + column.ToString();
LineColumnLabel = "Line: " + currentLineNumber.ToString() + " Column: " + column.ToString();
}
最佳答案
在 MSDN ( http://msdn.microsoft.com/en-us/library/system.windows.controls.richtextbox.caretposition%28v=vs.110%29.aspx ) 上有一个针对您的任务的标准示例。请注意,在此上下文中,“光标”称为“插入符号”。来自 MSDN 的示例如下:
// Create a new FlowDocument, and add 3 paragraphs.
FlowDocument flowDoc = new FlowDocument();
flowDoc.Blocks.Add(new Paragraph(new Run("Paragraph 1")));
flowDoc.Blocks.Add(new Paragraph(new Run("Paragraph 2")));
flowDoc.Blocks.Add(new Paragraph(new Run("Paragraph 3")));
// Set the FlowDocument to be the content for a new RichTextBox.
RichTextBox rtb = new RichTextBox(flowDoc);
// Get the current caret position.
TextPointer caretPos = rtb.CaretPosition;
// Set the TextPointer to the end of the current document.
caretPos = caretPos.DocumentEnd;
// Specify the new caret position at the end of the current document.
rtb.CaretPosition = caretPos;
关于c# - WPF 中 RichTextBox 内的光标位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24420235/