Sunday, May 31, 2015

Auto Expand WPF TextBox Height


There weren't many direct explanations on the internet to achieve this, so I thought of briefly blogging it here. If you want to auto expand the Textbox to a certain height and then stop and enable the vertical scroll bar from that point onwards, please use have a look at the following sample Textbox declaration in XAML:

   <TextBox Width="500"
       
        MinWidth="100"

        Margin="{StaticResource TextCommentMargin}" 
                                                                            VerticalContentAlignment="Center" 
                                                                            VerticalAlignment="Center" 
                                                                            MinHeight="{StaticResource TextCommentHeight}" 
                                                                            MaxHeight="75.0" 
                                                                            Height="Auto"
                                                                            TextWrapping="Wrap"
                                                                            AcceptsReturn="True" 
                                                                            VerticalScrollBarVisibility="Auto">

The important properties to enable this auto expand feature are; MaxHeight, Height, TextWrapping and VerticalScrollBarVisibility. 
  • Setting the MaxHeight to a certain height limits the Textbox from growing beyond that limit
  • Setting 'Height' to 'Auto' (a non numerical value) is the core to this feature, which enable the textbox to grow as contents fit.
  • Setting TextWrapping to 'Wrap' basically breaks off the sentence when it reaches the tip of the width of the text box.
  • Setting VerticalScrollBarVisibility to 'Auto', will enable the vertical scroll bars, once the text attempts to go beyond the MaxHeight of the Textbox.
All other properties are optional. The AcceptsReturn property provides you with a choice that whether you need to accept carriage returns within the Textbox or not.

I hope this helps somebody.