wpf 如何在文本框中只允许数字和减号“-”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31676779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to Only allow numbers and a Minus "-" in a Textbox
提问by CareTaker22
I would like to know how I would be able to allow only numbersand a "-"minus sign in a textbox?
我想知道如何才能在文本框中只允许数字和“-”减号?
Here is coding that I can already allow only numbers:
这是我已经可以只允许数字的编码:
private void txtDicountSettlement_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
Regex regex = new Regex("[^0-9]+");
e.Handled = regex.IsMatch(e.Text);
}
回答by James Thorpe
Just add the -to your regex character group, in a position that's not making a range of characters:
只需将-加到您的正则表达式字符组中,其位置不会产生一系列字符:
private void txtDicountSettlement_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
Regex regex = new Regex("[^0-9-]+");
e.Handled = regex.IsMatch(e.Text);
}
回答by blue
I think you want something like this
我想你想要这样的东西
^[0-9-]*$
It will match any digit any time and n no of dashes and will ignore any other character
它会在任何时候匹配任何数字并且没有破折号,并且会忽略任何其他字符
回答by loli
[^-]+[^0-9]+should prevent any input that's not an integer or a negative integer.
[^-]+[^0-9]+应该防止任何不是整数或负整数的输入。
回答by DeshDeep Singh
Add a preview text input event. Like so: <TextBox PreviewTextInput="PreviewTextInput" />.
添加预览文本输入事件。像这样:<TextBox PreviewTextInput="PreviewTextInput" />。
Then inside that set the e.Handled if the text isn't allowed.
然后在里面设置 e.Handled 如果文本不被允许。
e.Handled = !IsTextAllowed(e.Text);
I use a simple regex in IsTextAllowed to see if I should allow what they've typed. In my case I only want to allow numbers, dots and dashes.
我在 IsTextAllowed 中使用了一个简单的正则表达式来查看我是否应该允许他们输入的内容。就我而言,我只想允许数字、点和破折号。
private static bool IsTextAllowed(string text)
{
Regex regex = new Regex("[^0-9.-]+"); //regex that matches disallowed text
return !regex.IsMatch(text);
}
If you want to prevent pasting of incorrect data hook up the DataObject.Pasting event DataObject.Pasting="TextBoxPasting"as shown here (code excerpted):
如果您想防止粘贴不正确的数据,请连接 DataObject.Pasting 事件DataObject.Pasting="TextBoxPasting",如下所示(代码摘录):
// Use the DataObject.Pasting Handler
private void TextBoxPasting(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(String)))
{
String text = (String)e.DataObject.GetData(typeof(String));
if (!IsTextAllowed(text))
{
e.CancelCommand();
}
}
else
{
e.CancelCommand();
}
}
回答by darson1991
private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (!char.IsDigit(e.Text, e.Text.Length - 1))
{
if(e.Text.Length != 0 || (e.Text.Length == 0 && e.Substring(e.Text.Length - 1) != "-"))
e.Handled = true;
}
}
回答by ABDUL REHMAN
Here is the best solution for numeric Textbox and This is answer by Answer!
这是数字文本框的最佳解决方案,这是答案的答案!
private bool IsOKForDecimalTextBox(char theCharacter, TextBox theTextBox)
{
// Only allow control characters, digits, plus and minus signs.
// Only allow ONE plus sign.
// Only allow ONE minus sign.
// Only allow the plus or minus sign as the FIRST character.
// Only allow ONE decimal point.
// Do NOT allow decimal point or digits BEFORE any plus or minus sign.
if (
!char.IsControl(theCharacter)
&& !char.IsDigit(theCharacter)
&& (theCharacter != '.')
&& (theCharacter != '-')
&& (theCharacter != '+')
)
{
// Then it is NOT a character we want allowed in the text box.
return false;
}
// Only allow one decimal point.
if (theCharacter == '.'
&& theTextBox.Text.IndexOf('.') > -1)
{
// Then there is already a decimal point in the text box.
return false;
}
// Only allow one minus sign.
if (theCharacter == '-'
&& theTextBox.Text.IndexOf('-') > -1)
{
// Then there is already a minus sign in the text box.
return false;
}
// Only allow one plus sign.
if (theCharacter == '+'
&& theTextBox.Text.IndexOf('+') > -1)
{
// Then there is already a plus sign in the text box.
return false;
}
// Only allow one plus sign OR minus sign, but not both.
if (
(
(theCharacter == '-')
|| (theCharacter == '+')
)
&&
(
(theTextBox.Text.IndexOf('-') > -1)
||
(theTextBox.Text.IndexOf('+') > -1)
)
)
{
// Then the user is trying to enter a plus or minus sign and
// there is ALREADY a plus or minus sign in the text box.
return false;
}
// Only allow a minus or plus sign at the first character position.
if (
(
(theCharacter == '-')
|| (theCharacter == '+')
)
&& theTextBox.SelectionStart != 0
)
{
// Then the user is trying to enter a minus or plus sign at some position
// OTHER than the first character position in the text box.
return false;
}
// Only allow digits and decimal point AFTER any existing plus or minus sign
if (
(
// Is digit or decimal point
char.IsDigit(theCharacter)
||
(theCharacter == '.')
)
&&
(
// A plus or minus sign EXISTS
(theTextBox.Text.IndexOf('-') > -1)
||
(theTextBox.Text.IndexOf('+') > -1)
)
&&
// Attempting to put the character at the beginning of the field.
theTextBox.SelectionStart == 0
)
{
// Then the user is trying to enter a digit or decimal point in front of a minus or plus sign.
return false;
}
// Otherwise the character is perfectly fine for a decimal value and the character
// may indeed be placed at the current insertion position.
return true;
}
and Then Call This Function in the Key Press Event Like As
然后在按键事件中调用此函数,如 As
public void Allow_Only_Numeric(object sender, KeyPressEventArgs e)
{
try
{
TextBox textbox = (TextBox)sender;
Console.WriteLine(textbox.Text);
if(IsOKForDecimalTextBox(e.KeyChar,textbox) == true)
{
e.Handled = false;
}
else
{
e.Handled = true;
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}

