简体   繁体   English

如何强制文本框只接受WPF中的数字?

[英]How to force textbox to take only numbers in WPF?

I want user to enter only numeric values in TextBox . 我希望用户只在TextBox输入数值。

I got this code: 我得到了这段代码:

private void txtType1_KeyPress(object sender, KeyPressEventArgs e)
{
     int isNumber = 0;
     e.Handled = !int.TryParse(e.KeyChar.ToString(), out isNumber);
}

But I am not getting textbox_KeyPress event and e.KeyChar while using WPF. 但是在使用WPF时我没有得到textbox_KeyPress事件和e.KeyChar

Whats the solution in WPF? 什么是WPF的解决方案?

Edit:

I made a Solution! 我做了一个解决方案!

private void txtName_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
    CheckIsNumeric(e);
}

private void CheckIsNumeric(TextCompositionEventArgs e)
{
    int result;

    if(!(int.TryParse(e.Text, out result) || e.Text == "."))
    {
        e.Handled = true;
    }
}
protected override void OnPreviewTextInput(TextCompositionEventArgs e)
    {
        char c = Convert.ToChar(e.Text);
        if (Char.IsNumber(c))
            e.Handled = false;
        else
            e.Handled = true;

        base.OnPreviewTextInput(e);
    }

You can use a validation rule... http://www.codeproject.com/KB/WPF/wpfvalidation.aspx 您可以使用验证规则... http://www.codeproject.com/KB/WPF/wpfvalidation.aspx

Or make your own Maskable textbox http://rubenhak.com/?p=8 或制作自己的Maskable文本框http://rubenhak.com/?p=8

You can bind your textbox with a dependency property and inside dependency property's validation method you can check if int.tryparse returns true then fine otherwise you can go for default or you can reset value. 您可以使用依赖项属性和内部依赖项属性的验证方法绑定文本框,您可以检查int.tryparse是否返回true,否则您可以使用默认值,也可以重置值。

Or you can use WPF ValidationRules to find out when the value is changed. 或者,您可以使用WPF ValidationRules找出值的更改时间。 Once changed you can apply logic for inout validaiton. 一旦更改,您可以应用inout validaiton的逻辑。

Or you can use IDataError Info for validation. 或者您可以使用IDataError Info进行验证。

In WPF the keycode values are different from the normal winforms e.keychar values, 在WPF中,键码值与正常的winforms e.keychar值不同,

In the PreviewKeyDown event of the textbox, add this code: 在文本框的PreviewKeyDown事件中,添加以下代码:

if ((e.key < 34) | (e.key > 43)) {
if ((e.key < 74) | (e.key > 83)) {
    if ((e.key == 2)) {
        return;
        }
    e.handled = true;
    }
}

This will allow the User to only enter Numbers in the Numpad0 - Numpad9 section and the D0 - D9 and also the key.Back 这将允许用户只输入Numpad0 - Numpad9部分中的Numbers和D0 - D9以及key.Back

Hope this Helps, cheers! 希望这有助于,欢呼!

bit enhanced version of Hasib Uz Zaman Hasib Uz Zaman的位增强版

     private void txtExpecedProfit_PreviewTextInput_1(object sender, TextCompositionEventArgs e)
    {
        CheckIsNumeric((TextBox)sender,e);
    }

    private void CheckIsNumeric(TextBox sender,TextCompositionEventArgs e)
    {
        decimal result;
        bool dot = sender.Text.IndexOf(".") < 0 && e.Text.Equals(".") && sender.Text.Length>0;
        if (!(Decimal.TryParse(e.Text, out result ) || dot )  )
        {
            e.Handled = true;
        }
    }

this will check for duplication .(decimal mark) and will not allow just only .(decimal mark) 这将检查重复。(十进制标记)并且不会仅允许。(十进制标记)

//Call this code on KeyDown Event
if((e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || (e.Key == Key.Back))
{ e.Handled = false; }
else if((e.Key >= Key.D0 && e.Key <= Key.D9))
{ e.Handled = false; }
else
{ e.Handled = true; }
private void shomaretextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
  // xaml.cs code
  if (!char.IsDigit(e.Text, e.Text.Length - 1))
    e.Handled = true;
}

In xaml 在xaml

<TextBox x:Name="shomaretextBox" 
         HorizontalAlignment="Left" 
         Height="28" 
         Margin="125,10,0,0" 
         TextWrapping="Wrap" 
         VerticalAlignment="Top" 
         Width="151" 
         Grid.Column="1"        
         TextCompositionManager.PreviewTextInput="shomaretextBox_PreviewTextInput" />

我相信你正在寻找的是PreviewTextInput事件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM