每次按下 "ENTER" 键时,如何将行号附加到多行文本框中每一行的开头?

How to append line numbers to the beginning of every line in a multi-line textbox every time the "ENTER" key is pressed?

我经历了这些,但它们对我的情况没有帮助

这在我的情况下不起作用,因为它在答案中包含 KeyData 或 KeyCode 方法,当我尝试 运行 时显示错误。

我试过这个在我的情况下不起作用,因为它在按下按钮时使用 Adding new line of data to TextBox

这个只是添加了一些字符串,例如 first、second、third 和 that is ,这对我的情况没有帮助。 https://www.codeproject.com/Questions/320713/Adding-new-line-in-textbox-without-repalcing-exist

我在 Google 中浏览了 20 个搜索结果,其中许多不相关,而其他则对我的情况没有帮助。

如果我很好地理解了这个问题,您想在文本框中添加每个新行的行号。为此,您需要使用 KeyDown 事件

在视图中添加 TextBox
<TextBox KeyDown="TextBox_KeyDown" x:Name="txtBox" />

然后,在视图的代码隐藏中,您可以检查键是否为 "enter" 键并将行号添加到文本

private void TextBox_KeyDown(object sender, KeyEventArgs e)
{
    if (e.Key == Key.Enter)
    {
        string txt = txtBox.Text;
        int lineNumber = txt.Split('\n').Length + 1;
        txtBox.Text += '\n' + lineNumber.ToString();
        txtBox.CaretIndex = txtBox.Text.Length;
    }
}

注释

  • txtBox.CaretIndex = txtBox.Text.Length; 行在编辑文本后将插入符号置于文本末尾。否则,当您按回车键时,插入符号将重置为文本的开头。
  • 当文本框为空时,您需要附加第一行号。
  • 您可能需要处理编辑,例如,这样用户就无法删除行号。

编辑

如果使用 TextBoxAcceptsReturn 属性,事件 KeyDown 直接由 TextBox 处理,并向父级发送注释。在这种情况下,您必须使用 PreviewKeyDown 事件,请参阅 MSDN Routing Strategies

我尝试了 computhoms 的答案,但它并没有完全按照我想要的方式工作。

首先,KeyDown 事件没有产生任何结果,似乎在按下 Enter 键时,KeyDown 事件没有触发,也没有产生任何结果。 所以我改用了 PreviewKeyDown 事件。

其次没有写第一行的行号。同样对于后续数字,它会在新行中创建数字,然后将光标移动到另一行,因此效果如下:

一些文字

2

一些文字

3

一些文字

等等。

我想要的结果是这样的:

1-一些文本。

2-一些文本。

3-一些文本。

所以我修改了 Computhos 给出的代码,它给了我正确的结果。 这是我使用的代码:

在 xaml 中创建 TextBox 并像这样创建 PreviewKeyDown 事件后

  <TextBox  PreviewKeyDown="LifeGoalsTextBox_PreviewKeyDown" x:Name="LifeGoalsTextBox" TextWrapping="Wrap" AcceptsReturn="True" VerticalScrollBarVisibility="Auto" />

我去后面的代码写了这段代码:

private void LifeGoalsTextBox_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                string txt = LifeGoalsTextBox.Text;
                int lineNumber = txt.Split('\n').Length ;
                string lineNumberString = lineNumber.ToString();

                if (lineNumber == 0)
                {
                    LifeGoalsTextBox.Text = LifeGoalsTextBox.Text.Insert(0, "1") + '-';
                }
                else
                {
                    lineNumber++;
                    int lastLine = 1 + LifeGoalsTextBox.Text.LastIndexOf('\n');
                    LifeGoalsTextBox.Text = LifeGoalsTextBox.Text.Insert(lastLine, lineNumberString+ '-') ;

                    LifeGoalsTextBox.CaretIndex = LifeGoalsTextBox.Text.Length;
                }
            }
        }