TextBox:修改用户的输入

问题描述 投票:2回答:2

当用户添加;时,我想在TextBox中添加; + 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)
        );
    }
}

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

你能解释一下如何控制用户输入并保持撤销堆栈吗?

c# wpf input textbox
2个回答
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
投票

该解决方案有效:

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

海达尔,你能复制这个解决方案吗?我验证了你的答案(你努力工作)。

© www.soinside.com 2019 - 2024. All rights reserved.