In a Windows Phone 7 app. I happen to have many TextBox
s stacked in a ItemsControl
and the behaviour across textboxes for selection is not uniform
Just found a neat trick! On a single tap of a TextBox control it gets focus and on GotFocus
routine using SelectionStart
property of TextBox one can get the current character which has the caret just before it. With this data the left and right boundaries with space character can be found and thus the word selected.
private void textBox_GotFocus(object sender, RoutedEventArgs e)
{
TextBox txtBox = (TextBox)sender;
char [] strDataAsChars = txtBox.Text.ToCharArray();
int i = 0;
for (i = txtBox.SelectionStart - 1; ((i >= 0) &&
(strDataAsChars[i] != ' ')); --i) ;
int selBegin = i + 1;
for (i = txtBox.SelectionStart; ((i < strDataAsChars.Length) &&
(strDataAsChars[i] != ' ')); ++i) ;
int selEnd = i;
txtBox.Select(selBegin, selEnd - selBegin);
}
Posted it here so that it may help someone later on.