2009-05-21 74 views

回答

6

检查文本框的keydown事件,做作为

  // If escape is presses, then close the window. 
      if(Key.Escape == e.Key) 
      { 
       this.Close(); 
      } 
      // Allow alphanumeric and space. 
      if(e.Key >= Key.D0 && e.Key <= Key.D9 || 
       e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9 || 
       e.Key >= Key.A && e.Key <= Key.Z || 
       e.Key == Key.Space) 
      { 
       e.Handled = false; 
      } 
      else 
      { 
       e.Handled = true; 
      } 

      // If tab is presses, then the focus must go to the 
      // next control. 
      if(e.Key == Key.Tab) 
      { 
       e.Handled = false; 
      } 

希望这将帮助......

+0

BTW,处理程序的签名是: 私人无效OnKeyDownHandler(对象发件人,发送KeyEventArgs E) – Jeff 2013-10-31 20:11:01

0

KeyDown事件处理程序可能不是最好的地方,因为该字符已经被添加到TextBox中。您可以响应PreviewKeyDown事件并阻止该事件继续,但这可能会导致未知结果。

一种方法是将ValidationRule附加到TextBox。虽然这不会阻止用户输入角色,但会通知他们他们不被允许。要做到这一点,你从System.Windows.Controls.ValidationRule推导得到的东西是这样的:

public class MyValidationRule : ValidationRule 
{ 
    public override ValidationResult Validate(object value, CultureInfo cultureInfo) 
    { 
     // Logic to determine if the TextBox contains a valid string goes here 
     // Maybe a reg ex that only matches alphanumerics and spaces 
     if(isValidText) 
     { 
      return ValidationResult.ValidResult; 
     } 
     else 
     { 
      return new ValidationResult(false, "You should only enter an alphanumeric character or space"); 
     } 
    } 
} 

,然后用它在XAML这样的:

<TextBox> 
    <TextBox.Text> 
     <Binding Path="MyString" 
       UpdateSourceTrigger="PropertyChanged"> 
      <Binding.ValidationRules> 
       <myns:MyValidationRule /> 
      </Binding.ValidationRules> 
     </Binding> 
    </TextBox.Text> 
</TextBox> 

每次用户输入无效字符他们会得到错误信息。希望这有一些用处。

0

您还可以使用文本框的PreviewTextInput事件。

<TextBox Name="txtName" PreviewTextInput="txtName_PreviewTextInput"/> 

并添加代码下面的背后:

private void txtName_PreviewTextInput(object sender, TextCompositionEventArgs e) 
    { 
     foreach (char c in e.Text) 
     { 
      if (!char.IsLetterOrDigit(c)) 
      { 
       e.Handled = true; 
       break; 
      } 
     } 
    } 
0

我DONOT认为这是一个很好的做法是使用的KeyDown。 退步是你将不得不处理Backspace,删除和标签键也。

相反: 手柄PreviewTextInput

private void OnPreviewTextInput(object sender, TextCompositionEventArgs e) 
    { 
     if (!IsMatch(e.Text)) e.Handled = true; 
    } 

    private bool IsMatch(string input) 
    { 
     return Regex.IsMatch(input, MyRegexString); 
    } 

则必须照顾PasteHandler的: 添加下面的构造线。

DataObject.AddPastingHandler(TargetTextBoxName, PasteHandler); 

    private void PasteHandler(object sender, DataObjectPastingEventArgs e) 
     { 
      if (!e.DataObject.GetDataPresent(typeof(string))) return; 
      // Allow pasting only numeric 
      var pasteText = e.DataObject.GetData(typeof(string)) as string; 
      if (!IsMatch(pasteText)) 
      { 
       e.CancelCommand(); 
      } 
     } 
+0

你的正则表达式将是 “^ [A-ZA-Z0-9]” – kkk 2015-12-03 17:39:24

相关问题