WPF TextBox 只能输入数字键

 <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" 就可以了。

时间: 2024-10-12 07:44:30

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

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

1.设置textbox属性InputMethod.IsInputMethodEnabled="False" 2.增加KeyDown事件 private void TextBox_KeyDown(object sender, KeyEventArgs e) { #region --对输入中文就没办法屏蔽,可以在Textbox添加属性InputMethod.IsInputMethodEnabled="False"-- //屏蔽非法按键 if (e.Key >= K

wpf 限制textbox只能输入数字及特殊键

原文:wpf 限制textbox只能输入数字及特殊键 使用vs2015进行wpf设计时,发现限制输入数字时,Keydown事件无法检测到空格的输入,后经过查资料调试,发现PreviewKeyDown可以满足检测输入所有值合法性的要求,我的textbox输入框中只允许输入(大小键盘中)的数字0-9,以及删除回车,左右方向键,tab键,删除键,下面代码为限制 private void MinSpaceTextBox_PreviewKeyDown(object sender, KeyEventArgs

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

/* *设置textBox只能输入数字(正数,负数,小数) */ public static bool NumberDotTextbox_KeyPress(object sender, KeyPressEventArgs e) { //允许输入数字.小数点.删除键和负号 if ((e.KeyChar < 48 || e.KeyChar > 57) && e.KeyChar != 8 && e.KeyChar != (char)('.') && e

Asp.net TextBox只能输入数字

原文:Asp.net TextBox只能输入数字 <asp:textbox id="TextBox1" onkeyup="if(isNaN(value))execCommand('undo')" runat="server" Width="80px" onafterpaste="if(isNaN(value))execCommand('undo')"></asp:textbox> 其

Asp.net控制TextBox只能输入数字

在Asp.net开发中,为了确保数据的正确性,经常要对用户输入的内容进行验证,比如说用户只能输入数字,不能输入中文和英文,这如何实现呢?下面我们来看看.    实现过程,在TextBox控件中加两个属性事件:<asp:TextBox ID="txtName" runat="server" Width="175px" style="ime-mode:disabled" onkeypress="if (event.

winform 中TextBox只能输入数字

textBox1.KeyPress+=TextNumber_KeyPress; private void TextNumber_KeyPress(object sender, KeyPressEventArgs e) { var tb = (TextBox) sender; if (e.KeyChar != Convert.ToChar(13)) { if (e.KeyChar != 8 && !char.IsDigit(e.KeyChar)) { MessageShow("只能

UWP textbox 只能输入数字

private void Testbox_TextChanged(object sender, TextChangedEventArgs e) {    var textbox = (TextBox)sender;    if (!Regex.IsMatch(textbox.Text, "^\\d*\\.?\\d*$") && textbox.Text != "")   {     int pos = textbox.SelectionStart -

C# TextBox 只能输入数字

private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { TextBox txt = sender as TextBox; //屏蔽非法按键,只能输入小数 if ((e.KeyChar >= '0' && e.KeyChar <= '9') || e.KeyChar == '-' || e.KeyChar == '.' || e.KeyChar == 8) { if (txt.Text.Contai

textbox只能输入数字或中文的常用正则表达式和验证方法

验证数字的正则表达式集 验证数字:^[0-9]*$ 验证n位的数字:^\d{n}$ 验证至少n位数字:^\d{n,}$ 验证m-n位的数字:^\d{m,n}$ 验证零和非零开头的数字:^(0|[1-9][0-9]*)$ 验证有两位小数的正实数:^[0-9]+(.[0-9]{2})?$ 验证有1-3位小数的正实数:^[0-9]+(.[0-9]{1,3})?$ 验证非零的正整数:^\+?[1-9][0-9]*$ 验证非零的负整数:^\-[1-9][0-9]*$ 验证非负整数(正整数 + 0):^\d