2009-05-21 5 views

Répondre

6

Vérifiez l'événement KeyDown de la zone de texte et faire comme

  // 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; 
      } 

Espérons que cela aidera ......

+0

BTW, la signature du gestionnaire est: OnKeyDownHandler private void (object sender, KeyEventArgs e) – Jeff

0

Le gestionnaire d'événements KeyDown n'est peut-être pas le meilleur endroit pour cela, car le caractère a déjà été ajouté au TextBox. Vous pouvez répondre à l'événement PreviewKeyDown et empêcher l'événement de se poursuivre, mais cela pourrait avoir des conséquences inconnues.

Une approche consiste à attacher une ValidationRule à la zone de texte. Bien que cela n'empêche pas l'utilisateur d'entrer dans le personnage, il les avertit qu'ils ne sont pas autorisés à le faire. Pour ce faire, vous dérivez de System.Windows.Controls.ValidationRule pour obtenir quelque chose comme ceci:

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"); 
     } 
    } 
} 

Et puis utilisez dans XAML comme ceci:

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

Chaque fois que l'utilisateur entre un caractère non valide ils obtiendraient le message d'erreur. J'espère que c'est utile.

0

Vous pouvez également utiliser l'événement PreviewTextInput de la zone de texte.

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

Et d'ajouter ce qui suit dans votre code derrière:

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

Je pense que DONOT est une bonne pratique à utiliser KeyDown. L'inconvénient est que vous devrez gérer les touches Backspace, delete et tab aussi.

Au lieu de cela: poignée 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); 
    } 

alors doit prendre soin de PasteHandler: ajouter la ligne suivante dans le constructeur.

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

votre regex sera "^ [a-zA-Z0-9]" – kkk

Questions connexes