I recently experienced a strange behavior of text boxes.
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="200"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Label Content="Test"/>
<TextBox Grid.Column="1" TextWrapping="Wrap" Text="testtesttesttesttesttesttesttesttesttesttest"/>
<Control Grid.Row="1" Grid.ColumnSpan="2" Width="280"/>
</Grid>
In this example code I have a Grid
with 2 rows and 2 columns. The 2nd column is set to a fixed width. The TextBox
has TextWrapping
set to Wrap
.
In the second row I have a Control
with a fixed width that is higher than the Grid
would normally be. This increases the ActualWidth
of the second column from 200 to about 250.
The actual width of the TextBox
also increases to match the new width of the column.
When I now add a long string to the text box the text, it doesn't use the full width of the TextBox
but instead wraps way to early and leaves about 40 pixels at the end of the TextBox
empty.
I've found out that the TextBox
has a readonly ExtentWidth
property. This property is responsible for the wrapping. In my example the values of the ExtentWidth
is about 180, which is the 200 from the width of the grid column minus margins and paddings.
What can I do to fix the wrapping in the TextBox
?
EDIT: This question is not a duplicate of Looking for explanation for WPF Grid ColumnSpan behavior. That question explains what happens to the Widths of the grid columns. But it doesn't answer the question regarding the wrapping behavior of the TextBox.