WPF TextBox限制输入控制
设置TextBox只能输入整数和小数;
<TextBox x:Name="textBox" Width="100" Height="22" input:InputMethod.IsInputMethodEnabled="False" PreviewTextInput="textBox_PreviewTextInput" LostFocus="tb_TMX_PWMDuty_LostFocus"/>
private void textBox_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
var textElem = (sender as TextBox);
if(textElem.Text.StartsWith("0") && textElem.Text.Length == 1)
{
if (e.Text == "0")
{
e.Handled = true;
return;
}
else if (e.Text == ".")
{
e.Handled = false;
}
else
textElem.Text = "";
}
if(textElem.Text.Length == 0 && e.Text == ".")
{
e.Handled = true;
textElem.Text = "0.";
textElem.SelectionStart = textElem.Text.Length;
return;
}
//解决连续输入很多.
if ((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 tb_TMX_PWMDuty_LostFocus(object sender, RoutedEventArgs e)
{
var textElem = (sender as TextBox);
if (textElem.Text.EndsWith("."))
textElem.Text = textElem.Text.Remove(textElem.Text.Length - 1,1);
}