WPF中TextBox限制输入不起作用的问题

时间:2024-06-26 16:35:14

最近再用textbox做限制输入时遇到一个莫名其妙的问题:

首先看代码:

<TextBox  Name="txtip1" Height="40" Width="60" FontSize="20"  MaxLength="3"  TextChanged="TextBox_TextChanged">

private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            try
            {
                //屏蔽中文输入和粘贴输入
                System.Windows.Controls.TextBox textBox = sender as System.Windows.Controls.TextBox;
                if (textBox == null) return;
                TextChange[] change = new TextChange[e.Changes.Count];
                e.Changes.CopyTo(change, 0);

int offset = change[0].Offset;
                if (change[0].AddedLength > 0)
                {
                    double num = 0;
                    if (!Double.TryParse(textBox.Text, out num))
                    {
                        textBox.Text = textBox.Text.Remove(offset, change[0].AddedLength);
                        textBox.Select(offset, 0);
                    }
                }

if (ComConvert.TryInt(textBox.Text) > 255)
                {
                    textBox.Text = textBox.Text.Remove(textBox.Text.Length - 1);

textBox.SelectionStart = textBox.Text.Length;
                }
            }
            catch (Exception ex)
            {
                WinMessage.Show("输入数字有问题,请重新输入!");
            }

}

感觉代码没有一点问题,可代码运行时,发现所做的限制不起作用,如果把textBox.Text = textBox.Text.Remove(textBox.Text.Length - 1); 这一句注释掉,虽然MaxLength属性又生效了,但是又不能限制数字不大于255,而且中文输入法还是可以输入。原本以为在TextChanged事件中再判断一下长度就好了,测试却发现只能生效一次,后面就又不起作用了。又尝试了KeyDown事件,发现还是一样。怎么办呢?

解决方法很简单:只要在TextBox中将InputMethod.IsInputMethodEnabled属性设为false即可,该属性还可以屏蔽中文输入法