使用事件:
PreviewTextInput
PreviewKeyUp
PreviewMouseRightButtonUp
页面代码:
<TextBox x:Name="avg_cha_value" HorizontalAlignment="Left" Margin="678,180,0,0" Text="" VerticalAlignment="Top" Style="{StaticResource input2}" PreviewTextInput="quYangWenDu_PreviewTextInput" PreviewKeyUp="quYangWenDu_PreviewKeyUp" PreviewMouseRightButtonUp="quYangWenDu_PreviewMouseRightButtonUp" />
private void quYangWenDu_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
var textElem = (sender as TextBox);
//解决连续输入很多.
if ((
textElem.Text.StartsWith(".") || string.IsNullOrWhiteSpace(textElem.Text)
|| textElem.Text.Contains(".")
) && e.Text == ".")
{
e.Handled = true;
return;
}
//禁止在0前面继续输入0
int index = ((System.Windows.Controls.TextBox)e.Source).CaretIndex;
if (textElem.Text.StartsWith("0.") && index == 0 && e.Text=="0")
{
e.Handled = true;
return;
}
//不能输入非数字
if (Regex.IsMatch(e.Text, @"[^\d+\.{0,1}\d+]+"))
{
e.Handled = true;
return;
}
}
private void quYangWenDu_PreviewKeyUp(object sender, KeyEventArgs e)
{
TextBox textBox = sender as TextBox;
if (!string.IsNullOrWhiteSpace(textBox.Text))
{
if (textBox.Text == "0.0" || textBox.Text.StartsWith("00"))
{
textBox.Text = textBox.Text.Replace("00", "");
}
if (!textBox.Text.StartsWith("0.") && Regex.IsMatch(textBox.Text, @"0+[1-9]+\.*\d+", RegexOptions.IgnoreCase))
{
textBox.Text = textBox.Text.TrimStart('0');
}
//输入的不是小数或正整数
Regex regex = new Regex(@"[^\d+\.{0,1}\d+]", RegexOptions.IgnoreCase);
textBox.Text = regex.Replace(textBox.Text, "");
}
}
//禁用右键粘贴字符串。//创建时间:2022-12-5 14:56:01
private void quYangWenDu_PreviewMouseRightButtonUp(object sender, MouseButtonEventArgs e)
{
e.Handled = true;
}
扩展,允许输入数字:+89.254,-68.542,15.324,748
//检查输入字符串是否为数字
private void numberCheck_PreviewKeyUp(object sender, KeyEventArgs e)
{
TextBox textBox = sender as TextBox;
if (!string.IsNullOrWhiteSpace(textBox.Text))
{
//输入小于两个字符不处理
if (textBox.Text.Length<2)
{
e.Handled = true;
return;
}
if (textBox.Text == "0.0" || textBox.Text.StartsWith("00"))
{
textBox.Text = textBox.Text.Replace("00", "");
}
if (!textBox.Text.StartsWith("0.") && Regex.IsMatch(textBox.Text, @"0+[1-9]+\.*\d+", RegexOptions.IgnoreCase))
{
textBox.Text = textBox.Text.TrimStart('0');
}
输入的不是小数或正整数
//Regex regex = new Regex(@"[^\d+\.{0,1}\d+]", RegexOptions.IgnoreCase);
//textBox.Text = regex.Replace(textBox.Text, "");
//准许输入+89.253,-12.36585,9,457
Regex regex2 = new Regex(@"(\+|\-)?\d+\.?\d*", RegexOptions.IgnoreCase);
textBox.Text = regex2.Match(textBox.Text).Value;
}
}
只准输入正整数
//只准输入正整数
private void txtTimeSpan_KeyUp(object sender, KeyEventArgs e)
{
TextBox textBox = txtTimeSpan; // sender as TextBox;
if (!string.IsNullOrWhiteSpace(textBox.Text))
{
if (textBox.Text == "0.0" || textBox.Text.StartsWith("00"))
{
textBox.Text = textBox.Text.Replace("00", "");
}
//只准输入正整数
//Regex regex2 = new Regex(@"(\+|\-)?\d+\.?\d*", RegexOptions.IgnoreCase);
Regex regex2 = new Regex(@"\d+", RegexOptions.IgnoreCase);
textBox.Text = regex2.Match(textBox.Text).Value;
}
}