#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"/>

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.



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.


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