如何在TextBox中编写时自动添加点

Tim*_*nov 5 c# wpf xaml

我有一个TextBox绑定DateTime类型.我需要在前2个字符和第2个字符后得到一个点,例如:12.12.1990.我在TextChanged事件中使用行为,代码:

void tb_TextChanged(object sender, TextChangedEventArgs e)
{
    int i = tb.SelectionStart;
    if (i == 2 || i == 5)
    {                
        tb.Text += ".";
        tb.SelectionStart = i + 1;
    }
}
Run Code Online (Sandbox Code Playgroud)

这是有效的,但如果我想通过退格删除文本,显然我不能删除点,因为事件再次被调用.

有什么更好的方法来解决它?

解决了

它可以工作但是如果可以,你可以修复我的算法.

        public string oldText = "";
        public string currText = "";
        private void TextBox1_TextChanged(object sender, TextChangedEventArgs e)
        {
            oldText = currText;
            currText = TextBox1.Text;
            if (oldText.Length > currText.Length)
            {
                oldText = currText;
                return;
            }
            if (TextBox1.Text.Length == currText.Length)
            {
                if (TextBox1.SelectionStart == 2 || TextBox1.SelectionStart == 5)
                {
                    TextBox1.Text += ".";
                    TextBox1.SelectionStart = TextBox1.Text.Length;
                }
            }

        }
Run Code Online (Sandbox Code Playgroud)

Geo*_*e T 1

我会在 KeyPress 事件中执行此操作,以便您可以按其类型进行过滤(使用 KeyChar 参数与 Char.IsLetter() 和类似函数)。

另外,按下下一个键时添加点。如果用户输入了“12”,则先不要添加点。当用户按 1 添加第二个“12”时,然后添加它(在新字符之前)。