小编Tim*_*nov的帖子

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

我有一个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 …
Run Code Online (Sandbox Code Playgroud)

c# wpf xaml

5
推荐指数
1
解决办法
1757
查看次数

标签 统计

c# ×1

wpf ×1

xaml ×1