TextBox: изменить ввод пользователя - PullRequest
0 голосов
/ 05 сентября 2018

Когда пользователь добавляет ;, я хочу добавить ; + Environment.NewLine в TextBox.

Я нахожу это решение:

private void TextBox_OnPreviewTextInput(object sender, TextCompositionEventArgs e)
{
    if (e.Text == ";")
    {
        e.Handled = true;
        TextCompositionManager.StartComposition(
                new TextComposition(InputManager.Current,
                (IInputElement)sender,
                ";" + Environment.NewLine)
        );
    }
}

Но после этого отмена не работает.

Можете ли вы объяснить мне, как контролировать пользовательский ввод и сохранить стек отмены?

Ответы [ 2 ]

0 голосов
/ 05 сентября 2018

Это решение работает:

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

Гейдар, можешь скопировать это решение? И я подтверждаю ваш ответ (вы делаете тяжелую работу).

0 голосов
/ 05 сентября 2018

-------------- Обновленный код по запросу ---------

Используйте это вместо этого и 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;
    }
}

Желаю тебе всего наилучшего, Гейдар

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...