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

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

问题描述

我们正在寻找一种方法,让文本框在用户输入时替换某些字符.注意,我们关注的是控件本身,而不是绑定、视图模型等.为了这个问题,假设有一个窗口,中间有一个文本框,没有别的.没有数据、没有视图模型、没有绑定等.

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.

我已经更新了这个问题,因为下面的所有答案似乎都集中在绑定、依赖属性、强制等方面.虽然我很欣赏这些建议,但如上所述,我们的控件不是绑定控件,所以它们不是适用.

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天全站免登陆