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

。_饼干妹妹 提交于 2019-12-18 07:10:37

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/6193027/selecting-the-tapped-on-word-on-a-single-click-in-textbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!