Preventing horizontal expansion of TextBox 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 in the whole solution, we use it in every text field that needs a short text.

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

Everything works fine, but then the client complains that some fields were set on older monitors with lower resolution, so I placed the ScrollViewer on one of the higher nodes of the visual tree to prevent snapping.

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

It is strange that TextBox es with the above style begin to expand to the right, instead of wrapping the text.

Is there a way to prevent this without ScrollViewer ?

+7
source share
4 answers

You must define the MaxWidth for the TextBox , otherwise there is no limit, because ScrollViewer .

+4
source

If you don't want to hardcode the width, you can go to bind the element to the width of the parent element ... here is an example

Here I bind the maxbox of the text box with the actual width of the scrolviewer .., and also you need to make sure that the width of the column width should be set to "*" and not to "Auto". if you set it to Auto, it will neglect the width of the ScrollViewer and continue to expand the width of the ScrollViewer and text field. I think you fall into this case ....

 <Grid> <Grid.ColumnDefinitions> <ColumnDefinition Width="*"></ColumnDefinition> <ColumnDefinition Width="*"></ColumnDefinition> </Grid.ColumnDefinitions> <ScrollViewer HorizontalScrollBarVisibility="Auto" Name="scv"> <TextBox Height="30" TextWrapping="Wrap" MaxWidth="{Binding ElementName=scv,Path=ActualWidth}"></TextBox> </ScrollViewer> </Grid> 
+7
source

The solution from @bathineni helped me solve my problem. Here is what worked for me:

  <Grid > <Grid.ColumnDefinitions> <ColumnDefinition Width="50"/> <ColumnDefinition Width="*"/> </Grid.ColumnDefinitions> <Button Grid.Column="0" Width="30" Height="23" Margin="10,5" Content="..."/> <ScrollViewer Grid.Column="1" HorizontalScrollBarVisibility="Disabled" verticalScrollBarVisibility="Disabled" Name="scv"> <TextBox Height="25" Text="Insert here long text" MaxWidth="{Binding ElementName=scv, Path=ActualWidth}" HorizontalAlignment="Stretch" /> </ScrollViewer> </Grid> 
+4
source

It works for me. If you want scrollbars to appear in the text box, you can add

 HorizontalScrollBarVisibility="Auto" VerticalScrollBarVisibility="Auto" 

in textbox

0
source

All Articles