【发布时间】:2016-01-17 05:57:26
【问题描述】:
例如,在 TextBox(TextBlock) C# WPF 中键入时
美丽的自然
beautiful_(这里,在输入nature之前,我想知道插入符号当前位置的索引。假设'_'下划线现在正在闪烁插入符号)
我要实现的是通过按 LeftShift 按钮设置选择的起始位置,并通过按 RightShift 按钮设置结束位置 这样我就可以仅在 textBox 中以编程方式选择最新(最近)的单个单词,以便在某处使用。
我一直在尝试使用以下简单代码的几种方法,但都失败了,并且在互联网上没有与我类似的案例..
或者作为更好的解决方案,有没有人知道一种方法,在完全输入美丽的自然之后,只按一次按键,以编程方式选择最近的单词“自然”?
如果有人为此分享卓越,我将不胜感激。
int startinglocation;
int endinglocation;
int selectionlength;
private void textBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key==Key.LeftShift) After typing Beautiful in textBox,
{
// To know the current location of Caret, Some wise instruction is needed here
}
if (e.Key == Key.RightShift) // After typing Nature in textBox,
{
// To know the current location of Caret, Some wise instruction is needed here
int selectionlength=endinglocation- startinglocation;
textBox.Select(startinglocation, selectionlength);
}
}
已解决
后者是 Nicolas Tyler 仅通过按一个键按钮来选择最近的最新单词的更好解决方案。谢谢泰勒先生。
private void textBox1_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.RightShift)
{
selectWord();
}
}
private void selectWord()
{
int cursorPosition = textBox1.SelectionStart;
int nextSpace = textBox1.Text.IndexOf(' ', cursorPosition);
int selectionStart = 0;
string trimmedString = string.Empty;
if (nextSpace != -1)
{
trimmedString = textBox1.Text.Substring(0, nextSpace);
}
else
{
trimmedString = textBox1.Text;
}
if (trimmedString.LastIndexOf(' ') != -1)
{
selectionStart = 1 + trimmedString.LastIndexOf(' ');
trimmedString = trimmedString.Substring(1 + trimmedString.LastIndexOf(' '));
}
textBox1.SelectionStart = selectionStart;
textBox1.SelectionLength = trimmedString.Length;
}
【问题讨论】:
标签: c# wpf textbox location caret