wpf怎么让Textbox只能输入数字
1个回答
展开全部
废话不多说,直接上代码。
首先在界面中添加一个TextBox
<TextBox Name="txt_group_userNo" DataObject.Pasting="txt_group_userNo_Pasting" InputMethod.IsInputMethodEnabled="False" PreviewKeyDown="txt_group_userNo_PreviewKeyDown" PreviewTextInput="txt_group_userNo_PreviewTextInput" Width="100" ></TextBox>
然后再后台代码中实现事件
#region 控制文本框只能输入数字
private void txt_group_userNo_Pasting(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(String)))
{
String text = (String)e.DataObject.GetData(typeof(String));
if (!isNumberic(text))
{ e.CancelCommand(); }
}
else { e.CancelCommand(); }
}
private void txt_group_userNo_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space)
e.Handled = true;
}
private void txt_group_userNo_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (!isNumberic(e.Text))
{
e.Handled = true;
}
else
e.Handled = false;
}
public static bool isNumberic(string _string)
{
if (string.IsNullOrEmpty(_string))
return false;
foreach (char c in _string)
{
if (!char.IsDigit(c) && c.ToString() != "*")
//if(c<'0' c="">'9')//最好的方法,在下面测试数据中再加一个0,然后这种方法效率会搞10毫秒左右
return false;
}
return true;
}
#endregion
首先在界面中添加一个TextBox
<TextBox Name="txt_group_userNo" DataObject.Pasting="txt_group_userNo_Pasting" InputMethod.IsInputMethodEnabled="False" PreviewKeyDown="txt_group_userNo_PreviewKeyDown" PreviewTextInput="txt_group_userNo_PreviewTextInput" Width="100" ></TextBox>
然后再后台代码中实现事件
#region 控制文本框只能输入数字
private void txt_group_userNo_Pasting(object sender, DataObjectPastingEventArgs e)
{
if (e.DataObject.GetDataPresent(typeof(String)))
{
String text = (String)e.DataObject.GetData(typeof(String));
if (!isNumberic(text))
{ e.CancelCommand(); }
}
else { e.CancelCommand(); }
}
private void txt_group_userNo_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space)
e.Handled = true;
}
private void txt_group_userNo_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (!isNumberic(e.Text))
{
e.Handled = true;
}
else
e.Handled = false;
}
public static bool isNumberic(string _string)
{
if (string.IsNullOrEmpty(_string))
return false;
foreach (char c in _string)
{
if (!char.IsDigit(c) && c.ToString() != "*")
//if(c<'0' c="">'9')//最好的方法,在下面测试数据中再加一个0,然后这种方法效率会搞10毫秒左右
return false;
}
return true;
}
#endregion
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询