<Grid>
        <TextBox Name="textBox1" PreviewTextInput="textBox1_PreviewTextInput" 
                 HorizontalAlignment="Stretch"   VerticalAlignment="Center"   />
    </Grid>
1
2
3
4
5
6
        //using System.Text.RegularExpressions;
        private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
            Regex re = new Regex("[^0-9.-]+");
            e.Handled = re.IsMatch(e.Text);
        }

KeyDown事件:2011-04-28优化Tab And RightCtrl


 private void tbCount_KeyDown(object sender, KeyEventArgs e)
{
TextBox txt = sender as TextBox; //屏蔽非法按键
if ((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal || e.Key.ToString() == "Tab")
{
if (txt.Text.Contains(".") && e.Key == Key.Decimal)
{
e.Handled = true;
return;
}
e.Handled = false;
}
else if (((e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod) && e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
{
if (txt.Text.Contains(".") && e.Key == Key.OemPeriod)
{
e.Handled = true;
return;
}
e.Handled = false;
}
else
{
e.Handled = true;
if (e.Key.ToString() != "RightCtrl")
{
MessageBox.Show(this.Resources["Txt_InnerPage_ConnPointManage_TabMyConnPoint_AddMyCloudSeeNum_Prompt"].ToString(), this.Resources["Txt_InnerPage_ConnPointManage_TabMyConnPoint_AddMyCloudSeeNum_PromptTitle"].ToString(), MessageBoxButton.OK, MessageBoxImage.Warning);
}
}
}

TextChanged事件:


private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
//屏蔽中文输入和非法字符粘贴输入
TextBox textBox = sender as TextBox;
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);
}
}
}

在网上有不少关入这方面的资料,下面是我选用的一个方案

public NumberTextBox()
        {
            InitializeComponent();
            this.KeyDown += NumberTextBox_KeyDown;
            this.TextChanged += NumberTextBox_TextChanged;
        }

void NumberTextBox_KeyDown(object sender, KeyEventArgs e)
        {
            if ((e.Key >= Key.D0 && e.Key <= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))
            {
                e.Handled = false;
            }
            else
            {
                e.Handled = true;
            }
        }

void NumberTextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            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(this.Text, out num))
                {
                    this.Text = this.Text.Remove(offset, change[0].AddedLength);
                    this.Select(offset, 0);
                }
            }
        }

但是这个方案当输入法为中文的时候效果不理想,于是想到了禁用输入法。

引入xmlns:input="clr-namespace:System.Windows.Input;assembly=PresentationCore"

然后再 TextBox控件的xaml中  input:InputMethod.IsInputMethodEnabled="False" 就可以了。

WPF TextBox 只能输入数字键的更多相关文章

  1. wpf textbox只能输入数字,屏蔽中文输入

    1.设置textbox属性InputMethod.IsInputMethodEnabled="False" 2.增加KeyDown事件 private void TextBox_K ...

  2. C#设置textBox只能输入数字(正数,负数,小数)简单实现

    /* *设置textBox只能输入数字(正数,负数,小数) */ public static bool NumberDotTextbox_KeyPress(object sender, KeyPres ...

  3. Asp.net TextBox只能输入数字

    原文:Asp.net TextBox只能输入数字 <asp:textbox id="TextBox1" onkeyup="if(isNaN(value))execC ...

  4. TextBox只能输入数字

    Asp.net TextBox只能输入数字 <asp:textbox id="TextBox1" onkeyup="if(isNaN(value))execComm ...

  5. C# textbox中输入时加限制条件 // C#Winform下限制TextBox只能输入数字 // 才疏学浅(TextBox 小数点不能在首位+只能输入数字)

    textbox中输入时加限制条件 分类: C# winform2008-08-26 08:30 306人阅读 评论(0) 收藏 举报 textbox正则表达式object 1.用正则表达式! 2.使用 ...

  6. c# TextBox只能输入数字的处理方法(完整版各种情况考虑在内,可根据需求灵活修改)

    //选择文本框的事件窗口,找到按键输入的方法KeyPress,双击建立新的方法. /// <summary> /// textBox只能输入数字的处理方法 /// </summary ...

  7. [WinForm]TextBox只能输入数字或者正浮点型数字

    关键代码: /// <summary> /// 只能输入数字[KeyPress事件] /// </summary> /// <param name="textB ...

  8. winform 中TextBox只能输入数字

    textBox1.KeyPress+=TextNumber_KeyPress; private void TextNumber_KeyPress(object sender, KeyPressEven ...

  9. C# TextBox 只能输入数字

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { TextBox txt = sender as TextBox ...

随机推荐

  1. docker related,docker history

    History of an image and size of layers: docker history --no-trunc=true zabbix/zabbix-3.0 | tr -s ' ' ...

  2. MySQL安装后的设定及其变量(参数)的设置

    1.为所有root用户设定密码:mysql> SET PASSWORDmysql> update mysql.user SET password=PASSWORD("your_p ...

  3. Manacher专题

    1.POJ 3974 Palindrome 题意:求一个长字符串的最长回文子串. 思路:Manacher模板. #include<iostream> #include<algorit ...

  4. myql命令

    ALTER TABLE 表名 DROP COLUMN 列名#删除某一列

  5. dom树改变监听

    function unwrap(el, target) { if ( !target ) { target = el.parentNode; } while (el.firstChild) { tar ...

  6. 【leetcode刷题笔记】Restore IP Addresses

    Given a string containing only digits, restore it by returning all possible valid IP address combina ...

  7. 一个可以查询CSS属性兼容性的网站。

    平时遇到CSS属性是不是道理具体兼容哪些网站,就可以直接上这个网站查询啦.http://www.caniuse.com/ 这个是网站地址.  例如查询 inline-block属性兼容性 就可以看到 ...

  8. 【Flask】sqlalchemy 排序

    ### 排序:1. order_by:可以指定根据这个表中的某个字段进行排序,如果在前面加了一个-,代表的是降序排序.2. 在模型定义的时候指定默认排序:有些时候,不想每次在查询的时候都指定排序的方式 ...

  9. 主攻ASP.NET MVC4.0之重生:ASP.NET MVC Web API

    UserController代码: using GignSoft.Models; using System; using System.Collections.Generic; using Syste ...

  10. RPC与HTTP

    一.为什么需要RPC,而不是简单的HTTP接口? RPC(即Remote Procedure Call,远程过程调用),主要是基于TCP/IP协议:而HTTP服务主要是基于HTTP协议的.我们都知道H ...