Custom Textbox with WPF Dependency Property

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

 

Ebook Download
View all
Learn
View all