从插入符位置文本区域中提取文本 [英] Extract text from caret position textarea

查看:78
本文介绍了从插入符位置文本区域中提取文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法使用后面的WPF代码从textarea提取文本.

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

示例: 伦敦的晴天

如果光标设置在[d * ay]上,则应该返回day. *表示光标.

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

任何帮助将不胜感激.

推荐答案

这似乎可行,但是我不确定当插入号位于空格中间时,您希望它如何表现.照原样,它基本上返回接触插入符的最近的令牌.例如,短语伦敦的晴天"具有四个标记:晴天",白天",中"和伦敦".

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 = "";
}

这篇关于从插入符位置文本区域中提取文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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