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:
- public class ValidatedTextBox : TextBox
- {
- public ValidatedTextBox()
- {
-
- }/ <summary>
-
-
- public static readonly DependencyProperty IsSpaceAllowedProperty =
- DependencyProperty.Register("IsSpaceAllowed", typeof(bool), typeof(ValidatedTextBox));
- public bool IsSpaceAllowed
- {
- get
- {
- return (bool)base.GetValue(IsSpaceAllowedProperty);
- }
- set
- {
- base.SetValue(IsSpaceAllowedProperty, value);
- }
- }
- protected override void OnPreviewKeyDown(KeyEventArgs e)
- {
- base.OnPreviewKeyDown(e);
- if (!IsSpaceAllowed && (e.Key == Key.Space))
- {
- e.Handled = true;
- }
- }
- }
Step 2
Now, Use this in the .XAML file:
Add namespace of ValidatedTextBox.cs class file in .XAML like below:
- xmlns:CustomControls="clr-namespace: ValidatedTextBox;assembly= ValidatedTextBox "
Now, Use it like below:
- <CustomControls:ValidatedTextBox IsSpaceAllowed="False"
- x:Name="MyTextBox" />
It will not allow space into the textbox.