#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

About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #927 – Limiting the Size of a TextBox

  1. Pingback: Dew Drop – October 14, 2013 (#1,644) | Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: