如何验证文本框应该只允许WPF中按键事件的整数和一个点 [英] How to validate the text box should allow only integers and one dot on key down event in WPF
本文介绍了如何验证文本框应该只允许WPF中按键事件的整数和一个点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在按键时,我需要允许数字键盘和数字板上的唯一数字和一个点。
我尝试了什么:
At key down I need to allow the only digits and one dot through the both numberpad and digits board.
What I have tried:
if ((e.Key <= Key.D0 && e.Key >= Key.D9) || (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9))
{
e.Handled = true;
MessageBox.Show("I only accept numbers, sorry. :(");
}
plaese帮助我..
plaese help me..
推荐答案
请参考以下代码,
检查字符是否为数字的功能
Hi, just refer the following code,
Function to check whether a character is numeric or not
private bool AreAllValidNumericChars(string str)
{
foreach (char c in str)
{
if (c != '.')
{
if (!Char.IsNumber(c)) return false;
}
else
{
if (textBox.Text.Contains(".") == true)
{
return false;
}
else
{
return true;
}
}
}
return true;
}
只需在文本框的 PreviewTextInput 上调用此函数,如下所示,
Just call this function on PreviewTextInput of your textbox like below,
private void YourTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !AreAllValidNumericChars(e.Text);
base.OnPreviewTextInput(e);
}
这篇关于如何验证文本框应该只允许WPF中按键事件的整数和一个点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文