繁体   English   中英

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

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

我希望用户只在TextBox输入数值。

我得到了这段代码:

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

但是在使用WPF时我没有得到textbox_KeyPress事件和e.KeyChar

什么是WPF的解决方案?

Edit:

我做了一个解决方案!

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);
    }

您可以使用验证规则... http://www.codeproject.com/KB/WPF/wpfvalidation.aspx

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

您可以使用依赖项属性和内部依赖项属性的验证方法绑定文本框,您可以检查int.tryparse是否返回true,否则您可以使用默认值,也可以重置值。

或者,您可以使用WPF ValidationRules找出值的更改时间。 一旦更改,您可以应用inout validaiton的逻辑。

或者您可以使用IDataError Info进行验证。

在WPF中,键码值与正常的winforms e.keychar值不同,

在文本框的PreviewKeyDown事件中,添加以下代码:

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

这将允许用户只输入Numpad0 - Numpad9部分中的Numbers和D0 - D9以及key.Back

希望这有助于,欢呼!

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;
        }
    }

这将检查重复。(十进制标记)并且不会仅允许。(十进制标记)

//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;
}

在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