Extract text from caret position textarea

一世执手 提交于 2020-01-17 04:08:21

问题


I am having trouble to extract text from textarea using WPF code behind.

Example: Sunny day in London

if the cursor is set on [d*ay] it should return day. * for the cursor.

Any help will be appreciated.


回答1:


This seems to work but I am not sure how you want it to behave when the caret is in the middle of whitespace. As is, it basically returns the nearest token that is touching the caret. For example, the phrase "Sunny day in London" has four tokens: "Sunny", "day", "in", and "London".

string selection;

if (txtBox.Text.Length > 0)
{
    int startIndex = 0;

    for (int i = txtBox.CaretIndex - 1; i >= 0; i--)
    {
        if (String.IsNullOrWhiteSpace(txtBox.Text[i].ToString()))
        {
            startIndex = i;
            break;
        }
    }

    int length = txtBox.Text.Length - startIndex;

    for (int i = startIndex; startIndex + i <= txtBox.Text.Length - 1; i++)
    {
        if (String.IsNullOrWhiteSpace(txtBox.Text[startIndex + i].ToString()))
        {
            length = i;
            break;
        }
    }

    selection = txtBox.Text.Substring(startIndex, length);
}
else
{
    selection = "";
}


来源:https://stackoverflow.com/questions/10904614/extract-text-from-caret-position-textarea

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