在文本框中单击即可选择点击的单词 [英] Selecting the tapped-on word on a single click in textbox

查看:16
本文介绍了在文本框中单击即可选择点击的单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Windows Phone 7 应用程序中.我碰巧有许多 TextBox 堆叠在 ItemsControl 中,并且跨文本框进行选择的行为并不统一,即单击任何文本框中的任何单词都不会选择轻敲的词.首先单击以聚焦文本框,然后单击以实际选择单词;但是一旦文本框获得焦点,只需单击一下即可选择其中的任何单词,直到用户想要在另一个文本框中选择其他单词.有没有办法消除这种情况?可能是通过在 GotFocus 事件上引发假鼠标左键向下和向上事件?

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?

我所做的是,在 LeftMouseButtonDown(和向上)事件中,我存储了事件 args.在 GotFocus 上,我尝试使用存储的 args 引发事件,但用于引发事件的事件处理程序 var 始终为空,因此引发事件不会发生.我是 C# 的新手,所以我不确定我离题了.

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.

推荐答案

刚刚发现了一个巧妙的技巧!只需轻按一下 TextBox 控件,它就会获得焦点,并且在使用 TextBox 的 SelectionStart 属性的 GotFocus 例程上,可以获取其前面有插入符号的当前字符.有了这些数据,可以找到带有空格字符的左右边界,从而选择单词.

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.

这篇关于在文本框中单击即可选择点击的单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆