开发者

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

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 i.e. a single click on any word in any text box does not select the tapped word. First a click is consumed for focusing the text box and then another to actually select the word; but once the text box has focus, it's a single click to select any word within, until the user wants to select some other word in another textbox. Is there a way to neutralize this? May be by raising fake mouse left button down and up events on a GotFocus event?

What I did was, on a LeftMouseButtonDown (and up) Event I stored the event args. On a GotFocus, I tried to raise an event with the stored args, but the event handler var used to raise the event always is null, hence raise event doesn't happen. I'm new开发者_运维问答 to C# so I'm not sure where I'm digressing.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜