How to get the selected line in a Text Box?

c#, textbox, windows-phone, windows-phone-7, word-wrap

Solution

I figured this out myself:

Rect rec = textbox.GetRectFromCharacterIndex(textbox.SelectionStart);
double rectop = rec.Top;
double lineheight = text.LineHeight;
int result = (int)(rectop / lineheight + 1);

result = the selected line.

Problem

I have text box with text wrapping enabled in my Windows Phone 7 app, how do I get the line count at the character selected by the user? For example, if a text box it looked like this: ``` test text bo|x is here ``` , with "|" representing the selected character, the line count would be 3. I need to do this at any point in time, most specifically when the text is changed. I could count the number of newlines in a text box without text wrapping, but this is clearly a different scenario.

Original source