Hoe can I ensure that a user can only enter alphanumeric and space in a textbox on KeyDown event in WPF? No special characters allowed.
A:
The KeyDown event handler might not be the best place to do this, as the character has already been added to the TextBox. You could respond to the PreviewKeyDown event and prevent the event continuing, but this could have unknown consequences.
One approach would be to attach a ValidationRule to the TextBox. Although this wouldn't stop the user entering the character it would notify them that they aren't allowed to. To do this you derive from System.Windows.Controls.ValidationRule to get something like this:
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");
}
}
}
And then use it in XAML like this:
<TextBox>
<TextBox.Text>
<Binding Path="MyString"
UpdateSourceTrigger="PropertyChanged">
<Binding.ValidationRules>
<myns:MyValidationRule />
</Binding.ValidationRules>
</Binding>
</TextBox.Text>
</TextBox>
Each time the user enters an invalid character they'd get the error message. Hope that's of some use.
Paul
2009-05-21 13:03:34
A:
Check the keydown event of the textbox and do as
// 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;
}
Hope this will help......
Sauron
2009-05-26 08:58:52