wpf 限制文本框只允许十进制数字
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20351579/
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
Restrict textbox to allow only decimal numbers
提问by Mussammil
I have a requirement to make a decimal textbox (Money textbox) which:
我需要制作一个十进制文本框(Money 文本框),它:
- only allows numbers 0-9 (allow upper numpad keys 0-9 and right numpad keys 0-9);
- allows only one dot which don't appear on start.
- 只允许数字 0-9(允许上小键盘键 0-9 和右小键盘键 0-9);
- 只允许一个不在开始时出现的点。
Valid:
有效的:
- 0.5
- 1
- 1.5000
- 0.5
- 1
- 1.5000
Invalid:
无效的:
- .5
- 5.500.55
- .5
- 5.500.55
Edit
编辑
my code is :
我的代码是:
private void floatTextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
e.Handled = !TextBoxValidation.AreAllValidDecimalChars(e.Text);
}
public static class TextBoxValidation
{
public static bool AreAllValidDecimalChars(string str)
{
bool ret = false;
int x = 0;
foreach (char c in str)
{
x = (int)c;
}
if (x >= 48 && x <= 57 || x == 46)
{
ret = true;
}
return ret;
}
}
回答by Bas
If you want to allow copy and pasting as well you cannot do it with keyboard events. A TextBoxhas a TextChangedevent which allows you to handle this event appropirately. If you want to block any input that is not a number or dot you could handle it like this:
如果您还想允许复制和粘贴,则不能使用键盘事件来实现。ATextBox有一个TextChanged事件,它允许您适当地处理此事件。如果你想阻止任何不是数字或点的输入,你可以这样处理:
private void TextBox_TextChanged(object sender, TextChangedEventArgs e)
{
//get the textbox that fired the event
var textBox = sender as TextBox;
if (textBox == null) return;
var text = textBox.Text;
var output = new StringBuilder();
//use this boolean to determine if the dot already exists
//in the text so far.
var dotEncountered = false;
//loop through all of the text
for (int i = 0; i < text.Length; i++)
{
var c = text[i];
if (char.IsDigit(c))
{
//append any digit.
output.Append(c);
}
else if (!dotEncountered && c == '.')
{
//append the first dot encountered
output.Append(c);
dotEncountered = true;
}
}
var newText = output.ToString();
textBox.Text = newText;
//set the caret to the end of text
textBox.CaretIndex = newText.Length;
}
回答by Sheridan
You can achieve your goal by simply implementing two event handlers on a TextBox:
您可以通过简单地在 a 上实现两个事件处理程序来实现您的目标TextBox:
TextCompositionEventHandler textBox_PreviewTextInput =
new TextCompositionEventHandler((s, e) => e.Handled = !e.Text.All(
c => Char.IsNumber(c) || c == '.'));
KeyEventHandler textBox_PreviewKeyDown = new KeyEventHandler(
(s, e) => e.Handled = e.Key == Key.Space);
textBox.PreviewTextInput += textBox_PreviewTextInput;
textBox.PreviewKeyDown += textBox_PreviewKeyDown;

