在显示文本之前修改TextBox中的文本

时间:2017-04-13 17:11:50

标签: c# wpf textbox textchanged

我希望在显示之前修改TextBox中输入的Text,而不查看已经输入的Text。

示例: xaml:

<TextBox x:Name="tb" TextChanged="tb_TextChanged">
    my long text
</TextBox>

C#:

private void tb_TextChanged(object sender, TextChangedEventArgs e)
{
    TextBox tb = sender as TextBox;

    if (tb != null)
    {
        //save caretIndex
        int caretIndex = tb.CaretIndex;

        //modify Text //can be any modification
        //vvvvvvvvvvv Lines that I'm talking about

        tb.Text.ToLower(); //or: tb.Text.ToLower(); etc.

        char[] notAllowedChars = new char[] {'/t', '~', '#'}; //any other
        foreach (char c in notAllowedChars)
        {
            tb.Text = tb.Text.Replace(c, '_'); //replace unwanted characters
        }

        //^^^^^^^^^^^^ these lines modify the whole text

        //restore caretIndex
        tb.CaretIndex = caretIndex;
    }
}

在该示例中,将修改整个Text。但是所有其他角色都已经过修改。所以我不想再次通过它们了。我只想在插入之前修改更改的文本。

我说的是100.000+个字符。这意味着,查找所有字符会导致不必要的性能问题。

是否有任何解决方案或是不可能的需求。

1 个答案:

答案 0 :(得分:2)

您可以查看TextChangedEventArgs以查看更改,然后再次修改文本...以下是一些启动代码:

private bool m_bInTextChanged;
private void tb_TextChanged(object sender, TextChangedEventArgs e)
{
    if (m_bInTextChanged)
        return;

    m_bInTextChanged = true;

    TextBox tb = sender as TextBox;

    if (tb != null)
    {
        //save caretIndex
        int caretIndex = tb.CaretIndex;

        if (e.Changes.Any())
        {
            var addedchanges = e.Changes.Where(tc => tc.AddedLength > 0);

            foreach (var added in addedchanges)
            {
                string stringchanged = tb.Text.Substring(added.Offset, added.AddedLength);

                tb.Select(added.Offset, added.AddedLength);

                tb.SelectedText = stringchanged.ToLower();
            }
        }

        //restore caretIndex
        tb.CaretIndex = caretIndex;
    }

    m_bInTextChanged = false;
}