Jesse Johnston
{ ironic tagline here }

Scrolling TextBox in WPF

Thursday, 1 October 2009 03:03 by jesse

If you put a TextBox inside a ScrollViewer, the TextBox will take as much width as it needs, even if you set TextWrapping to Wrap.  That means that a long line of text will just stretch out to the right, beyond the right edge of the ScrollViewer, instead of wrapping.

Fortunately, you can bind the Width of the TextBox to the ScrollViewer ViewportWidth.  This makes the text wrap at the right edge of the ScrollViewer.  If you hide the horizontal scrollbar, you get just what you'd expect - vertical scrolling and horizontal wrapping.  This also allows the ScrollViewer to participate in a flow style layout and still have the text wrap correctly.

<ScrollViewer HorizontalScrollBarVisibility="Hidden" VerticalScrollBarVisibility="Auto">

<TextBox IsReadOnly="True" FontSize="14" TextWrapping="Wrap" Width="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type ScrollViewer}}, Path=ViewportWidth}"/>

</ScrollViewer>

 

Digg It!DZone It!StumbleUponTechnoratiRedditDel.icio.usNewsVineFurlBlinkList
Categories:   .NET | Silverlight | WPF
Actions:   E-mail | del.icio.us | Permalink | Comments (0) | Comment RSSRSS comment feed
Comments are closed