It will create a custom Textbox in WPF that will not allow space while typing. It will be created with the help of WPF Dependency property.

Step 1

Take a class and inherit it from “TextBox” class:

  1. public class ValidatedTextBox : TextBox
  2. {
  3. public ValidatedTextBox()
  4. {
  5. }/ <summary>
  6. /// Dependency property to get/set flag for allowing space character
  7. /// </summary>
  8. public static readonly DependencyProperty IsSpaceAllowedProperty =
  9. DependencyProperty.Register("IsSpaceAllowed", typeof(bool), typeof(ValidatedTextBox));
  10. public bool IsSpaceAllowed
  11. {
  12. get
  13. {
  14. return (bool)base.GetValue(IsSpaceAllowedProperty);
  15. }
  16. set
  17. {
  18. base.SetValue(IsSpaceAllowedProperty, value);
  19. }
  20. }
  21. protected override void OnPreviewKeyDown(KeyEventArgs e)
  22. {
  23. base.OnPreviewKeyDown(e);
  24. if (!IsSpaceAllowed && (e.Key == Key.Space))
  25. {
  26. e.Handled = true;
  27. }
  28. }
  29. }
Step 2

Now, Use this in the .XAML file:

Add namespace of ValidatedTextBox.cs class file in .XAML like below:
  1. xmlns:CustomControls="clr-namespace: ValidatedTextBox;assembly= ValidatedTextBox "
Now, Use it like below:
  1. <CustomControls:ValidatedTextBox IsSpaceAllowed="False"
  2. x:Name="MyTextBox" />
It will not allow space into the textbox.