#920 – TextBox Sizes to Fit Its Content

Unless you constrain the size of a TextBox, it will changs its width to fit its contents.  If the TextWrapping property is set to wrap, it will also change its height.

Whether the TextBox is constrained depends on the its parent container and the use of alignment properties.  In the example below, the HorizontalAlignment of the TextBox defaults to Stretch, so the TextBox sizes to its container, rather than to its content.

    <StackPanel Margin="5">
        <TextBox Text="This"/>
    </StackPanel>

920-001
However, if we set the HorizontalAlignment to Center, the TextBox will size to fit its content. It will change its width as we type, accommodating the new characters.

920-002

920-003

If we also set its TextWrapping property to Wrap, it will grow until it fills the available with and then increase its height to accommodate the text.

920-004

In most applications, you’ll want to constrain the TextBox to some maximum width and height.

About Sean
Software developer in the Twin Cities area, passionate about software development and sailing.

3 Responses to #920 – TextBox Sizes to Fit Its Content

  1. Pingback: Dew Drop – October 3, 2013 (#1,637) | Alvin Ashcraft's Morning Dew

  2. Pingback: Dew Drop – October 4, 2013 (#1,638) | Morning Dew

  3. Pingback: #927 – Limiting the Size of a TextBox | 2,000 Things You Should Know About WPF

Leave a comment