积极答复者
wpf中如何限制textbox中只能输入数字

问题
答案
-
你好 shuhang,
欢迎来MSDN中文论坛。
通过你的描述, 我认为你所关心的问题是:
--> 当用户按下=号键时进行其他操作但在textbox中不显示=号,我该无何去做?
如果我误解或者遗漏了你的问题,请你及时的告诉我。
对于你这个问题, 我想你可以用下面的代码解决:(根据你提供的代码写的)
else if (e.Key == Key.OemPlus)
{
MessageBox.Show("do something");
e.Handled = true;
}
因为WPF使用的是“事件路由”,如果你想了解更多关于 事件路由 的知识,你可以访问下面的链接:
http://msdn.microsoft.com/zh-cn/library/ms742806.aspx
针对你的问题,你想在用户输入“=”的时候,你要在 TextBox 不进行显示,其实就相当于停止WPF 事件路由 的传递,因此你可以使用“e.Handled = true;” 去完成你的目标。
如果你的问题还有疑问,请告诉我。
Best regards,
Sheldon _Xiao [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
- 已标记为答案 Sheldon _XiaoModerator 2010年12月27日 11:29
全部回复
-
你好 shuhang,
欢迎来MSDN中文论坛。
通过你的描述, 我认为你所关心的问题是:
--> 当用户按下=号键时进行其他操作但在textbox中不显示=号,我该无何去做?
如果我误解或者遗漏了你的问题,请你及时的告诉我。
对于你这个问题, 我想你可以用下面的代码解决:(根据你提供的代码写的)
else if (e.Key == Key.OemPlus)
{
MessageBox.Show("do something");
e.Handled = true;
}
因为WPF使用的是“事件路由”,如果你想了解更多关于 事件路由 的知识,你可以访问下面的链接:
http://msdn.microsoft.com/zh-cn/library/ms742806.aspx
针对你的问题,你想在用户输入“=”的时候,你要在 TextBox 不进行显示,其实就相当于停止WPF 事件路由 的传递,因此你可以使用“e.Handled = true;” 去完成你的目标。
如果你的问题还有疑问,请告诉我。
Best regards,
Sheldon _Xiao [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
- 已标记为答案 Sheldon _XiaoModerator 2010年12月27日 11:29
-
你好 shuhang,
我将把我的答复作为“答案”,这样有利于有同样问题的人找到答案,如果你认为我的回复对你的问题没有帮助,你可以取消作为答案。
Best regards,
Sheldon _Xiao [MSFT]
MSDN Community Support | Feedback to us
Get or Request Code Sample from Microsoft
Please remember to mark the replies as answers if they help and unmark them if they provide no help.
-
Xaml
<TextBox Height="23" HorizontalAlignment="Left" Margin="100,5,0,0" Name="textBox1" VerticalAlignment="Top" Width="120"
DataObject.Pasting="textBox1_Pasting" PreviewKeyDown="textBox1_PreviewKeyDown" InputMethod.IsInputMethodEnabled="False"
PreviewTextInput="textBox1_PreviewTextInput"
/>CS
//检测粘贴
private void textBox1_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 textBox1_PreviewKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Space)
e.Handled = true;
}private void textBox1_PreviewTextInput(object sender, TextCompositionEventArgs e)
{
if (!isNumberic(e.Text))
{
e.Handled = true;
}
else
e.Handled = false;
}
//isDigit是否是数字
public static bool isNumberic(string _string)
{
if (string.IsNullOrEmpty(_string))
return false;
foreach (char c in _string)
{
if (!char.IsDigit(c))
//if(c<'0' || c>'9')//最好的方法,在下面测试数据中再加一个0,然后这种方法效率会搞10毫秒左右
return false;
}
return true;
}你可以到http://www.wpf100.com/html/5/2012-03/article-138.html下载源码!