#928 – TextBox.MinLines Doesn’t Size Properly on Startup

When you give the MinLines property of a TextBox some value, you’ll find that the TextBox’s size isn’t adjusted to fit the minimum number of lines until after the user enters some text into the TextBox.  The TextBox will not initially be sized properly at startup.

You can work around this by doing the following:

  • Bind the Text property to some string-based property
  • At startup, set the value of the bound property to some text (e.g. a single space)
        <TextBox HorizontalAlignment="Stretch"
                 Margin="5"
                 Text="{Binding SomeText}"
                 MaxLines="3" MinLines="3"
                 VerticalScrollBarVisibility="Auto"/>

 

        public MainWindow()
        {
            this.InitializeComponent();
            this.DataContext = this;
            SomeText = " ";
        }

        private string someText;
        public string SomeText
        {
            get { return someText; }
            set
            {
                if (value != someText)
                {
                    someText = value;
                    RaisePropertyChanged("SomeText");
                }
            }
        }

928-001
You could also just manually set the TextBox to the desired size using the Height or MinHeight property.

#927 – Limiting the Size of a TextBox

By default, a TextBox is high enough to accommodate a single line of text and wide enough to accommodate it’s widest line.  The TextBox sizes to fits its content, even if the content changes at run-time.

For example, if we don’t constrain the size of a TextBox and then add and remove lines at run-time, its content will change:

        private void btnAdd_Click(object sender, RoutedEventArgs e)
        {
            MyText = MyText + Environment.NewLine +
                string.Format("This is line {0}", nextLine++);
        }

927-001

927-002

We can, however, constrain the height by setting the MinLines and MaxLines property of the TextBox.

        <TextBox Text="{Binding MyText}"
                 TextWrapping="NoWrap"
                 HorizontalAlignment="Center"
                 Margin="5"
                 MaxLines="2"/>

In the example above, when we continue adding lines, the TextBox still only shows two lines.
927-003
If we enabled a vertical scrollbar, we’d see that we actually have three lines (after adding three) and we could scroll down to the third line.

927-004