我想将TextBox中的输入限制为仅数字和点.
以及仅一个逗号,
和小数点分隔符
我尝试了以下方法:
char ch = e.Text[0];
if ((Char.IsDigit(ch) || ch == '.' || ch==','))
{
//Here TextBox1.Text is name of your TextBox
if ((ch == '.' && TextBox.Text.Contains('.')) || (ch==',' &&
TextBox.Text.Contains(',')))
e.Handled = true;
}
else
e.Handled = true;
但是使用这种方法只能放置一个点
答案 0 :(得分:1)
如何处理这样的PreviewTextInput
事件?
private void TextBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
TextBox textBox = (TextBox)sender;
e.Handled = !char.IsDigit(e.Text[0]) && e.Text[0] != '.' && (e.Text[0] != ',' || textBox.Text.Contains(","));
}
您可能还想处理Pasting
事件:
private void TextBox_Pasting(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(string)))
{
string text = (string)e.DataObject.GetData(typeof(String));
bool hasComma = false;
foreach (char c in text)
{
if (!char.IsDigit(c) && c != '.' && (c != ',' || hasComma))
e.CancelCommand();
hasComma = c == ',';
}
}
else
{
e.CancelCommand();
}
}
XAML:
<TextBox PreviewTextInput="TextBox_PreviewTextInput" DataObject.Pasting="TextBox_Pasting" />