2017-02-16 71 views
1

如何不允许空间,空白的,("_")从文本框中输入字符?如何通过键盘通过键盘(WPF,C#)不允许空间,空白的,(“_”)charachter从文本框中输入

我尝试代码:

Regex regex = new Regex(@"^[A-Za-z0-9\[\]/!$%^&*()\-_+{};:'£@#.?]*$"); 

,但是这部分代码禁止所有的字符,而不是空间。

+0

我也尝试␣,但没有什么是chaged。文本框等接受文本框中 – WPFwtf

+0

[Dublicate(空间http://stackoverflow.com/questions/10410882/how-can-i-modify-this-regular-expression-to-not-allow-white-spaces )? – Shakra

+3

如果你想做的事,而不是打字...用'KeyPress'事件,如果主要是32或Key.Space然后e.Handled = TRUE; –

回答

3

您可以添加PreviewKeyDown处理程序:

private void textBox_PreviewKeyDown(object sender, KeyEventArgs e) 
{ 
    if (e.Key == Key.Space) 
    { 
     e.Handled = true; 
    } 
} 

现在你的文本框会忽略空格。

0

根据你的目标,另一个选择是处理PreviewTextInput

{ 
     //... 
     TextBox tb = new TextBox(); 
     tb.PreviewTextInput += Tb_PreviewTextInput; 
} 

private void Tb_PreviewTextInput(object sender, TextCompositionEventArgs e) 
{ 
    if (e.Text == " ") 
     e.Handled = true; 
    base.OnPreviewTextInput(e); 
} 

例如,如果你想停止复制粘贴空间,这个建议。

在另一方面,如果你是指向您要插入到TextBox之前删除文本中的所有空格的情况,下面可能会有所帮助:

// ... 
    TextBox tb = new TextBox(); 
    tb.TextChanged += Tb_TextChanged; 
    // ... 

    bool _changing; 
    private void Tb_TextChanged(object sender, TextChangedEventArgs e) 
    { 
     if (_changing) 
      return; 
     _changing = true; 
     TextBox tb = (TextBox)sender; 
     string tx = tb.Text; 
     while (tx.Contains(" ")) 
      tx = tx.Replace(" ", string.Empty); 
     tb.Text = tx; 
     _changing = false; 
    } 

在这种情况下,看到this link了。