Selecting the tapped-on word on a single click in textbox

前端 未结 1 1112
别跟我提以往
别跟我提以往 2020-12-20 04:20

In a Windows Phone 7 app. I happen to have many TextBoxs stacked in a ItemsControl and the behaviour across textboxes for selection is not uniform

相关标签:
1条回答
  • 2020-12-20 05:00

    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.

    0 讨论(0)
提交回复
热议问题