TextBox:修改用户输入

时间:2018-09-04 21:45:00

标签: c# wpf input textbox

当用户添加.nvm/versions/node/v8.11.0 时,我想在文本框中添加;

我找到了这个解决方案:

; + Environment.NewLine

但是在此之后,撤消将不起作用。

您能解释一下如何控制用户输入并保留撤消堆栈吗?

2 个答案:

答案 0 :(得分:2)

--------------根据要求更新了代码---------

使用它代替它,并且100%有效。我对其进行测试以确保。

private void TextBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
    if (e.Text == ";")
    {
        // In this line remove preview event to  preventing event repeating
        ((TextBox)sender).PreviewTextInput -= TextBox_OnPreviewTextInput;

        // Whith this code get the current index of you Caret(wher you inputed your semicolon)
        int index = ((TextBox)sender).CaretIndex;

        // Now do The Job in the new way( As you asked)
        ((TextBox)sender).Text = ((TextBox)sender).Text.Insert(index, ";\r\n");

        // Give the Textbox preview Event again
        ((TextBox)sender).PreviewTextInput += TextBox_OnPreviewTextInput;

        // Put the focus on the current index of TextBox after semicolon and newline (Updated Code & I think more optimized code)
        ((TextBox)sender).Select(index + 3, 0);

        // Now enjoy your app
         e.Handled = true;
    }
}

祝你好运,盖达尔

答案 1 :(得分:1)

此解决方案有效:

private void TextBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
    if (e.Text == ";")
    {
        var textBox = (TextBox) sender;
        var selectStart = textBox.SelectionStart;
        var insertedText = ";" + Environment.NewLine;

        // In this line remove preview event to  preventing event repeating
        textBox.PreviewTextInput -= TextBox_OnPreviewTextInput;

        // Now do The Job
        textBox.Text = textBox.Text.Insert(selectStart, insertedText);

        // Give the TextBox preview Event again
        textBox.PreviewTextInput += TextBox_OnPreviewTextInput;

        // Put the focus after the inserted text
        textBox.Select(selectStart + insertedText.Length, 0);

        // Now enjoy your app
        e.Handled = true;
    }
}

Heydar,您可以复制此解决方案吗? 我会验证您的回答(您会努力工作)。