1

I have TextBox with MaxLength set to 10 but it is accepting 11 characters when Enter key is pressed. Looks like it is counting \n\r as 1 character instead of two. Is there anyway to make it count \n\r as two char length?

SamTh3D3v
  • 9,854
  • 3
  • 31
  • 47
Vasanth
  • 1,670
  • 1
  • 13
  • 17
  • Pretty hard to imagine a multi-line textbox accepting only 10 chars being useful. My crystal ball says that you forgot to set the AcceptsReturn property to False. – Hans Passant Sep 03 '15 at 16:21
  • 2
    Line breaks are indeed unlikely in a 10 character string, but the question is still relevant for higher numbers. (And why not allowing line breaks in a text which, let's say, will be stored in a fixed-size `char(10)` DB column?) – andreask Sep 03 '15 at 17:33

1 Answers1

1

If you really want to allow line breaks in your text box and limit its text length, I see two options:

  • Either bind MaxLength through a converter so that it changes its value according to how many line breaks (\r\n) the text contains, as shown in this question
  • Alternatively, you might define your own attached property MaxLength that calculates text length correctly. This might look somewhat like the following (just as an example you'll need to adapt that to take into account special cases etc.):

    public class TextBoxExtensions: DependencyObject
    {
        public static readonly DependencyProperty MaxLengthProperty = DependencyProperty.RegisterAttached(
            "MaxLength", typeof (int), typeof (MaxLengthBehavior), new PropertyMetadata(default(int), PropertyChangedCallback));
    
        public static void SetMaxLength(DependencyObject element, int value)
        {
            element.SetValue(MaxLengthProperty, value);
        }
    
        public static int GetMaxLength(DependencyObject element)
        {
            return (int) element.GetValue(MaxLengthProperty);
        }
    
        private static void PropertyChangedCallback(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs args)
        {
            var tb = dependencyObject as TextBox;
            if (tb != null)
            {
                tb.KeyDown -= TbOnKeyDown;
                tb.KeyDown += TbOnKeyDown;
            }
        }
    
        private static void TbOnKeyDown(object sender, KeyRoutedEventArgs args)
        {
            var tb = sender as TextBox;
            if (tb != null)
            {
                int max = GetMaxLength(tb);
                if (tb.Text.Length >= max)
                    args.Handled = true;
            }
        }
    }
    

<TextBox local:TextBoxExtensions.MaxLength="10" />

Community
  • 1
  • 1
andreask
  • 4,248
  • 1
  • 20
  • 25