WPF中设置TextBox只允许正负浮点数输入

控件属性:

禁用中文输入法

<Grid>
        <TextBox HorizontalAlignment="Left" Margin="69,217,0,0" Text="" TextWrapping="Wrap" VerticalAlignment="Top" Width="120" KeyDown="TextBox_KeyDown" PreviewTextInput="TextBox_PreviewTextInput" InputMethod.IsInputMethodEnabled="False"/>
    </Grid>

事件(不使用正则表达式):

按键事件:

private void TextBox_KeyDown(object sender, KeyEventArgs e)
        {
        if ((e.Key == Key.OemPeriod || e.Key == Key.OemMinus || e.Key == Key.Decimal || e.Key == Key.Subtract) && e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
                    {
                        e.Handled = false;
                    }//允许大小键盘的“.”和“-”输入
                    else if (((int)e.Key) >= 74 && ((int)e.Key) <= 84)
                    {
                        e.Handled = false;
                    }//允许小键盘数字输入
                    else if (((int)e.Key) >= 34 && ((int)e.Key) <= 43 && e.KeyboardDevice.Modifiers != ModifierKeys.Shift)
                    {
                        e.Handled = false;
                    }//允许大键盘数字输入
                    else
                        e.Handled = true;
        }

文本输入事件:

private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
        {
        var textelem = (sender as TextBox);
                    if (textelem.Text.StartsWith("0") && textelem.Text.Length == 1)
                    {
                        if (e.Text == "0")
                        {
                            e.Handled = true;
                            return;
                        }
                        else if (e.Text == ".")
                        {
                            e.Handled = false;
                        }
                        else
                            textelem.Text = "";
                    }
                    if (textelem.Text.Length == 0 && e.Text == ".")
                    {
                        e.Handled = true;
                        textelem.Text = "0.";
                        textelem.SelectionStart = textelem.Text.Length;
                        return;
                    }
                    if ((string.IsNullOrWhiteSpace(textelem.Text) || textelem.Text.Contains(".")) && e.Text == ".")
                    {
                        e.Handled = true;
                        return;
                    }
                    if (textelem.Text.Length > 0 && e.Text == "-")
                    {
                        e.Handled = true;
                        return;
                    }
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值