Search code examples
wpftextboxwhitespacemaxlength

TextBox MaxLength property is counting whitespace


My TextBox has a limit of 100 characters set by MaxLength property.

However, if the user types '\n' or '\t', they are counted as an additional character, which would make sense to the programmer, but not to the user.

Is there any workaround besides counting the characters by myself?


Solution

  • You could create your own attached property:

    <TextBox wpfApplication4:TextBoxBehaviors.MaxLengthIgnoringWhitespace="10" />
    

    With the attached property defined like this:

        public static class TextBoxBehaviors
    {
        public static readonly DependencyProperty MaxLengthIgnoringWhitespaceProperty = DependencyProperty.RegisterAttached(
            "MaxLengthIgnoringWhitespace",
            typeof(int),
            typeof(TextBoxBehaviors),
            new PropertyMetadata(default(int), MaxLengthIgnoringWhitespaceChanged));
    
        private static void MaxLengthIgnoringWhitespaceChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs eventArgs)
        {
            var textBox = dependencyObject as TextBox;
    
            if (textBox != null && eventArgs.NewValue is int)
            {
                textBox.TextChanged += (sender, args) =>
                    {
                        var maxLength = ((int)eventArgs.NewValue) + textBox.Text.Count(char.IsWhiteSpace);
                        textBox.MaxLength = maxLength;  
                    };
            }
        }
    
        public static void SetMaxLengthIgnoringWhitespace(DependencyObject element, int value)
        {
            element.SetValue(MaxLengthIgnoringWhitespaceProperty, value);
        }
    
        public static int GetMaxLengthIgnoringWhitespace(DependencyObject element)
        {
            return (int)element.GetValue(MaxLengthIgnoringWhitespaceProperty);
        }
    }
    

    The code will use the TextBox's existing MaxLength property and will just increase it by the number of white spaces you have entered. So if you set the property to 10 and type in 5 spaces, the actual MaxLength on the TextBox will be set to 15, and so on.