silverlight---TextBox只能输入数字或小数 屏蔽中文输入和非法粘贴: KeyDown事件处理方法

  private   void  txtRoomNum_KeyDown( object  sender, KeyEventArgs e)
{
    TextBox txt 
=  sender  as  TextBox;
    
// 屏蔽非法按键,只能输入整数
     if  ((e.Key  >=  Key.NumPad0  &&  e.Key  <=  Key.NumPad9))
    {
        e.Handled 
=   false ;
    }
    
else
    {
        e.Handled 
=   true ;
    }
}

private   void  txtRoomArea_KeyDown( object  sender, KeyEventArgs e)
{
    TextBox txt 
=  sender  as  TextBox;
    
// 屏蔽非法按键,只能输入小数
     if  ((e.Key  >=  Key.NumPad0  &&  e.Key  <=  Key.NumPad9)  ||  e.Key  ==  Key.Decimal)
    {
        
if  (txt.Text.Contains( " . " &&  e.Key  ==  Key.Decimal)
        {
            e.Handled 
=   true ;
            
return ;
        }
        e.Handled 
=   false ;
    }
    
else
    {
        e.Handled 
=   true ;
    }

}

 

 

参考一:
以下实现TextBox只能输入小数并且屏蔽中文输入和非法粘贴:
说明:以下实现均在Framework 3.0平台下

为TextBox加两个事件:TextChanged和KeyDown事件,具体如下:
KeyDown事件:

 1 private   void  TextBox_KeyDown( object  sender, System.Windows.Input.KeyEventArgs e)
 2          {
 3            TextBox txt = sender as TextBox;
 4
 5             //屏蔽非法按键
 6            if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal)
 7            {
 8                if (txt.Text.Contains("."&& e.Key == Key.Decimal)
 9                {
10                    e.Handled = true;
11                    return;
12                }

13                e.Handled = false;
14            }

15            else if (((e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod) && e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
16            {
17                if (txt.Text.Contains("."&& e.Key == Key.OemPeriod)
18                {
19                    e.Handled = true;
20                    return;
21                }

22                e.Handled = false;
23            }

24            else
25            {
26                e.Handled = true;
27            }

28        }

29
30
TextChanged事件
 1 private   void  TextBox_TextChanged( object  sender, TextChangedEventArgs e)
 2          {
 3            //屏蔽中文输入和粘贴输入
 4            TextBox textBox = sender as TextBox;
 5            TextChange[] change = new TextChange[e.Changes.Count];
 6            e.Changes.CopyTo(change, 0);
 7
 8            int offset = change[0].Offset;
 9            if (change[0].AddedLength > 0)
10            {
11                double num = 0;
12                if (!Double.TryParse(textBox.Text, out num))
13                {
14                    textBox.Text = textBox.Text.Remove(offset, change[0].AddedLength);
15                    textBox.Select(offset, 0);
16                }

17            }

18        }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值