How to check if the last line in a text field has only one word?

In the code below, I am assigning a string to a text field. The text of the text field is wrapped, so the words will be transferred to the next line if they cannot fit on one line.

WITH#

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 above example, it may happen that in the last line of the text box the word "Eyes" is the only word because of the wrap. If there is only one word in the last line, I would like to reduce the font size so that the last line has at least two words.

So, in short, there should never be just one word in the last line. It can have two or more words.

Example: (False)

 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 do not ask how to increase / decrease the font and on what basis the new font size should be calculated. This is another question I need to find out. But the first step in my problem is to find out if there is one word in the last line.

How to check if the last line in a text field has only one word?

+5
source share
2 answers

Perhaps a simple solution is to add inextricable space between the last words, that is:

 "...She closed her\u00a0eyes." 
+6
source

You can use the LineCount and GetLineText property to find the last line of text and then check to see if it contains a space (or any other separator you want).

+8
source

Source: https://habr.com/ru/post/1275539/


All Articles