您可以在输入时替换文本框中的字符吗? [英] Can you replace characters in a textbox as you type?

查看:103
本文介绍了您可以在输入时替换文本框中的字符吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们正在寻找一种方法,以使文本框在有人输入时替换某些字符.注意,我们专注于控件本身,而不是绑定,视图模型等.出于这个问题,假设有一个窗口,其中有一个文本框位于其中,而没有其他内容.没有数据,没有视图模型,没有绑定等.

We are looking for a way to make a textbox replace certain characters as a person types in it. Note, we are focusing on the control itself, not bindings, viewmodels, etc. For the sake of this question, assume there is a window with a textbox sitting in the middle of it and nothing else. No data, no viewmodel, no bindings, etc.

我已更新了问题,因为以下所有答案似乎都集中在绑定,依赖项属性,强制等方面.尽管我很欣赏建议(如上所述),但我们的控件不是绑定控件,因此它们不是"t适用.

I've updated the question because it seems all the answers below keep focusing on bindings, dependency properties, coersion, etc. While I appreciate the suggestions, as I stated above, our control is not a bound control so they aren't applicable.

现在,虽然我可以解释其原因,但由于这实际上是一个复杂且高级的用例,因此可使这篇文章的长度延长大约五倍,但这与问题本身无关,这就是为什么我要简化了场景,专注于我们要解决的特定问题,该问题与文本框控件有关,或者可能是您键入时替换字符的子类.

Now while I could explain the reasons for that, that would make this post about five times longer as it's actually a complex and advanced use-case, but that has nothing to do with the question itself, which is why I've simplified our scenario down to focus on the specific question we're trying to resolve, which is about a textbox control, or possibly a subclass of one replacing characters as you type.

希望现在更有意义.

推荐答案

实现此目的的最佳方法是使用TextChanged事件:

The best way to accomplish this is using the TextChanged event:

    private void OnTextChanged(object sender, TextChangedEventArgs e)
    {
        var tb = (TextBox)sender;
        using (tb.DeclareChangeBlock())
        {
            foreach (var c in e.Changes)
            {
                if (c.AddedLength == 0) continue;
                tb.Select(c.Offset, c.AddedLength);
                if (tb.SelectedText.Contains(' '))
                {
                    tb.SelectedText = tb.SelectedText.Replace(' ', '_');
                }
                tb.Select(c.Offset + c.AddedLength, 0);
            }
        }
    }

这有几个优点:

  • 您不必每次都遍历整个字符串,而只需遍历被替换的部分
  • 它在撤消管理器和粘贴文本中表现良好
  • 您可以轻松地将其封装到一个附加属性中,该属性可以应用于任何文本框

这篇关于您可以在输入时替换文本框中的字符吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆