<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. diff工具

    Beyond Compare 4  可以diff文件夹.单个文件.

  2. python并发编程&多线程(一)

    本篇理论居多,实际操作见:  python并发编程&多线程(二) 一 什么是线程 在传统操作系统中,每个进程有一个地址空间,而且默认就有一个控制线程 线程顾名思义,就是一条流水线工作的过程,一 ...

  3. Python Interpreter

    在开始之前,我们先限定下python解释器的意思.当讨论Python的时候,解释器这个词可以用在不同的地方.有的时候,解释器指的是Python Interpreter,也就是你在命令行交互界面上输入p ...

  4. NumPy基础知识:数组和矢量计算

    NumPy 的ndarray:一种多维数组对象 该对象是一个快速且灵活的大数据容器,可以利用这种数组对整个数据进行科学计算,语法跟标量元素之间的计算一样. 创建ndarray的方法: array函数: ...

  5. PhoneGap 兼容IOS上移20px(包括启动页,拍照)

    引自:http://stackoverflow.com/questions/19209781/ios-7-status-bar-with-phonegap 情景:在ios7下PhoneGap app会 ...

  6. 剑指offer 面试50题

    面试50题: 题目:第一个只出现一次的字符 题:在一个字符串(1<=字符串长度<=10000,全部由字母组成)中找到第一个只出现一次的字符,并返回它的位置. 解题思路一:利用Python特 ...

  7. eclipse修改web项目部署路径 wtpwebapps webapps 的设置

    eclipse修改web项目部署路径 wtpwebapps   webapps  的设置,在添加完server------>tomcat后,到server控制台进行设置 eclipse默认的部署 ...

  8. XP、win7下Excel 2007多窗口打开Excel的解决方法

    http://blog.x6x8.com/?p=330 Win7下的方法(借鉴了XP的方法): 1.先在桌面先建一个txt文件,将下面的代码复制进去 32位WIN7复制下面一行start “Excel ...

  9. python之路(sed,函数,三元运算)

    python之路(sed,函数,三元运算) 一.sed集合 1.set无序,不重复序列 2.创建 se = {11,22,33,33,44} list() #只要是一个类加上()自动执行 list _ ...

  10. 查看oracle当前连接数和进程数

    查询数据库当前进程的连接数: select count(*) from v$process; 查看数据库当前会话的连接数: select count(*) from v$session; 查看数据库的 ...