2017-08-02 123 views
2

我希望用户只能在TextBox中写入数字(0-9)。 我使用以下代码来防止用户编写除数字之外的字母和其他字符,但我无法避免用户使用TextBox中的空间。WPF TextBox no允许空间

private void CheckIsNumeric(TextCompositionEventArgs e) 
{ 
    int result; 

    if (!(int.TryParse(e.Text, out result))) 
    { 
     e.Handled = true; 
     MessageBox.Show("!!!no content!!!", "Error", 
         MessageBoxButton.OK, MessageBoxImage.Exclamation); 
    } 
} 

我媒体链接使用类似

if (Keyboard.IsKeyDown(Key.Space)) 
{ //...} 

试过,但没有成功。

感谢您的帮助。

+0

我试过了,它也允许空间。 – Morris

+0

对重复问题地址中接受的答案发表评论并支持该问题:“[Space]不会触发PreviewTextInput事件”。你从哪个事件中调用你的'CheckIsNumeric'方法? – dlatikay

+1

对不起,我一定忽略了这一点。 我正在使用PreviewTextInput事件,这将是问题。 我绕过了textbox.Text.Replace(“”,“”)的问题。所以现在所有的空间都被删除了,对我来说什么都好。 – Morris

回答

0

在检查之前检查空格是否分开,或只是更正空格。因此,用户可以尽可能多地进行空间分配,而且不会改变任何内容。

private void CheckIsNumeric(TextCompositionEventArgs e) 
{ 
    int result; 
    string removedSpaces = e.Text.Replace(" ",""); 
    if (!(int.TryParse(removedSpaces, out result))) 
    { 
     e.Handled = true; 
     MessageBox.Show("!!!no content!!!", "Error", 
         MessageBoxButton.OK, MessageBoxImage.Exclamation); 
    } 
} 
+0

感谢您的回答,但这不会改变任何内容。据我所知,PreviewTextInput事件不会对空间做出反应,所以我需要一个完全不同的方法。 – Morris

0

为您的文本框注册KeyPress事件 并添加此代码。

private void textBox_KeyPress(object sender, KeyPressEventArgs e) 
{ 
    if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.')) 
    { 
     e.Handled = true; 
    } 

    // If you want to allow decimal numeric value in you textBox then add this too 
    if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1)) 
    { 
     e.Handled = true; 
    } 
}