【发布时间】:2011-11-06 06:45:34
【问题描述】:
我正在开发一个 C# 语言的项目。我的问题是:如何检测鼠标光标下且位于“(”和“)”之间的字符串?
例如:当鼠标悬停在文本框中时,我想在文本框中突出显示“雅虎”:google(1) yahoo(2) apple(3) microsoft(4) ...
【问题讨论】:
我正在开发一个 C# 语言的项目。我的问题是:如何检测鼠标光标下且位于“(”和“)”之间的字符串?
例如:当鼠标悬停在文本框中时,我想在文本框中突出显示“雅虎”:google(1) yahoo(2) apple(3) microsoft(4) ...
【问题讨论】:
您可以将文本拆分为多个 TextBlock 运行...就像在网站中一样(使用 spans)...然后您可以在样式中点击 MouseOver 事件。
例子:
<TextBox>
<TextBox.Text>
<TextBlock Text="google" />
<TextBlock Text="(1) " />
<TextBlock Text="yahoo" />
<TextBlock Text="(2) " />
<TextBlock Text="apple" />
<TextBlock Text="(3) " />
<TextBlock Text="microsoft" />
<TextBlock Text="(4) " />
</TextBox.Text>
</TextBox>
然后为您想要的文本块的 IsMouseOver 添加样式。 (您也可以在代码中完成这一切)。
【讨论】:
TextBox.Text 是一个字符串属性,不接受StackPanel
TextBlock 也不是字符串类型。您将无法在 Text 的 TextBox 属性内使用任何类型的 UIElement
编辑
以下代码将直接选择鼠标下的单词
Xaml
<TextBox MouseMove="TextBox_MouseMove"
Text="Google(1) yahoo(2) apple(3) microsoft(4)"/>
背后的代码
private void TextBox_MouseMove(object sender, MouseEventArgs e)
{
TextBox textBox = sender as TextBox;
Point mousePoint = Mouse.GetPosition(textBox);
int charPosition = textBox.GetCharacterIndexFromPoint(mousePoint, true);
if (charPosition > 0)
{
textBox.Focus();
int index = 0;
int i = 0;
string[] strings = textBox.Text.Split(' ');
while (index + strings[i].Length < charPosition && i < strings.Length)
{
index += strings[i++].Length + 1;
}
textBox.Select(index, strings[i].Length);
}
}
【讨论】:
非常有趣的问题,我不马上知道答案,周围有类似的问题,不是开箱即用的解决方案,但如果你解决它并让它启发你,一个解决方案是可能的:
【讨论】: