第一步:
TextBox添加PreviewTextInput事件,如下:
正浮点数用下面方法:
-
//正浮点数
-
private void tbTest_PreviewTextInput(object sender,TextCompositionEventArgs e)
-
{
-
//匹配只能输入一个小数点的浮点数
-
Regex numbeRegex =
new Regex(
"^[.][0-9]+$|^[0-9]*[.]{0,1}[0-9]*$");
-
e.Handled =
-
!numbeRegex.IsMatch(
-
tbTest.Text.Insert(
-
tbTest.SelectionStart, e.Text));
-
tbTest.Text = tbTest.Text.Trim();
-
}
正整数用下面方法:
-
//正整数
-
private void tbTest_PreviewTextInput(object sender,TextCompositionEventArgs e)
-
{
-
Regex re =
new Regex(
"[^0-9.-]+");
-
e.Handled = re.IsMatch(e.Text);
-
}
第二步:
禁用文本框中输入法如下:
<TextBox Name="tb_Test" InputMethod.IsInputMethodEnabled="False"/>