wpfxamltextboxword-wrap

Prevent a TextBox from horizontal expanding in WPF


I have the following style defined in my App.xaml

<Style x:Key="textBoxMultiline" TargetType="{x:Type TextBox}" >
    <Setter Property="VerticalScrollBarVisibility" Value="Auto" />
    <Setter Property="HorizontalScrollBarVisibility" Value="Hidden" />
    <Setter Property="MinHeight" Value="50" />
    <Setter Property="TextWrapping" Value="Wrap" />
</Style>

And throughout the solution we're using it on every text box that needs a brief text.

<TextBox x:Name="textBoxDescription" Grid.Row="2" Grid.Column="1" Style="{DynamicResource textBoxMultiline}" />

Everything works great, but then the client complains about some fields were corped on older monitors with lower resolutions, so I placed a ScrollViewer on one of the higher visual tree nodes to prevent the corping.

<ScrollViewer Height="Auto" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto">
   ...
</ScrollViewer>

Strangely, the TextBoxes with the above style start expanding to the right instead of wrapping the text.

Is there a way to prevent this without removing the ScrollViewer?


Solution

  • You must define a MaxWidth for the TextBox, otherwise there's no limit because the ScrollViewer.