In the code below, I am assigning a string to text box. The text box text is wrapped, so words will be shifted to the next line if they cannot fit in same line.
C#:
textbox.Text = "Norma went to bed. It was eleven o'clock. She turned out the light. She lay in bed. It was dark. It was quiet. She couldn't sleep. She closed her eyes.";
XAML:
<TextBox
SelectionBrush="#FF54FF50"
x:Name="textbox"
Margin="10,53,0,0"
FontSize="24"
HorizontalAlignment="Left"
Width="341"
Height="285"
VerticalAlignment="Top"
TextChanged="Textbox_TextChanged"
IsReadOnly="True"
CaretBrush="Black"
BorderBrush="Black"
Foreground="Black"
FontWeight="Bold"
Grid.ColumnSpan="2"
Padding="0,5,0,0"
HorizontalContentAlignment="Center"
VerticalContentAlignment="Center"
VerticalScrollBarVisibility="Auto"
TextWrapping="Wrap" />
Now, with the example above, it may happen that on the last line in the text box the word "Eyes" is the only word due to wrapping. If the last line has only one word, I would like to decrease the font size so that the last line has at least two words.
So, in short, the last line should never have one word only. It may have two or more words.
Example: (Wrong)
Norma went to bed. It was
eleven o'clock. She turned
out the light. She lay in
bed. It was dark. It was
quiet. She couldn't
sleep. She closed her
eyes.
Example: (Right)
Norma went to bed. It was
eleven o'clock. She turned
out the light. She lay in
bed. It was dark. It was
quiet. She couldn't
sleep. She closed her eyes.
I am not asking how to increase/decrease the font and on what basis the new font size should be calculated. That is different question that I need to figure out. But first step of my problem is to find out if there is a single word in the last line.
How do I check if the last line in a text box has only one word?
You can use the LineCount
property and the GetLineText
method to find the last line of text and then check if it contains a space (or any other desired separator) in it.
Perhaps a simple solution is to add a non-breaking space between the last words, ie:
"...She closed her\u00a0eyes."
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With