C# 文本框:修改用户';s输入

C# 文本框:修改用户';s输入,c#,wpf,input,textbox,C#,Wpf,Input,Textbox,当用户添加一个,我想添加;+文本框中的Environment.NewLine 我发现这个解决方案: private void TextBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e) { if (e.Text == ";") { e.Handled = true; TextCompositionManager.StartComposition(

当用户添加一个
,我想添加
;+文本框中的Environment.NewLine

我发现这个解决方案:

private void TextBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
    if (e.Text == ";")
    {
        e.Handled = true;
        TextCompositionManager.StartComposition(
                new TextComposition(InputManager.Current,
                (IInputElement)sender,
                ";" + Environment.NewLine)
        );
    }
}
但是在这之后,撤销就不起作用了

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

------------根据要求更新代码--------- 用这个来代替,它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;
    }
}

祝你一切顺利,Heydar

感谢Heydar提供的解决方案。 我应用了一些改进:

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;
    }
}

关闭,撤消使用此解决方案的操作。但当我按下“;”时在句子的中间,“;\r\n”放在最后。我还按照你的要求更新了我的asnwer,请复制所有内容。不是它的一部分。我把注意力转移到了上一个索引上,因为我不明白“讨厌魔法3”这个词的意思。因为我们在文本中加了3个字符,所以我们必须向前走3步,直到插入符号移动到分号之后。这完全合乎逻辑。你能解释一下你的意思吗?回答的主要目的是让人理解/可读。为什么我更喜欢“\r\n”长度。当我阅读答案时,我不想费劲去理解问题的逻辑。这主要是哲学上的嗨,你测试过了吗?它能用吗?见兄弟我做了它更直接,在更少的代码没有安全壳和直接演员。是的,我承认安全强制转换对it安全更有利,但直接强制转换的编写速度更快,体积更小(我编写的代码只有6行),而且占用内存,性能可能更快。因为你要在文本框事件中使用这个事件,所以发送者不是别的什么。除非您添加到其他控件,否则它总是文本框。这是一个旧的改进建议。你可以忽略它。我按这个方向编辑了答案。