问题
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