c# - WPF 中 RichTextBox 内的光标位置

标签 c# wpf events richtextbox line-numbers

我正在开发一个小型 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/

相关文章:

c# - @model 关键字在 ASP.NET MVC View 中有什么作用?

c# - 负尺寸矩形如何相交?

.net - Entity Framework 6.1.3 中的 Citext 数据类型

c# - Linux Web 服务器和 .NET 客户端应用程序之间的实时通信

iphone - UISlider 事件

javascript - 加载 CSS 后触发的 jQuery 事件?

mysql 计划事件 'execute_at' 时间戳

c# - 使用 Razor LINQ .Where() 查找具有特定日期值的 Umbraco 节点

c# - 为什么 WPF 窗口在 MainWindow 关闭后不自动处理和收集?

c# - WPF ComboBox 绑定(bind)未正确更新