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

modify Text in TextBox before Text is displayed

我想在显示之前修改在文本框中键入的文本,而不查看已经键入的文本。

示例: 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;
    }
}

在该示例中,将修改整个文本。但是所有其他字符都已修改。所以我不想再经历它们。我只想在插入之前修改更改的文本。

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

有没有解决办法或者是不可能的需求

您可以查看 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;
}