【问题标题】:How to Select certain String that is under the Mouse Cursor in C#-wpf?如何在 C#-wpf 中选择鼠标光标下的某些字符串?
【发布时间】:2011-11-06 06:45:34
【问题描述】:

我正在开发一个 C# 语言的项目。我的问题是:如何检测鼠标光标下且位于“(”和“)”之间的字符串?

例如:当鼠标悬停在文本框中时,我想在文本框中突出显示“雅虎”:google(1) yahoo(2) apple(3) microsoft(4) ...

【问题讨论】:

    标签: c# .net wpf


    【解决方案1】:

    您可以将文本拆分为多个 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
    • 属性“文本”不支持“StackPanel”类型的值。
    • 谢谢,我忘了你不需要堆栈面板(而且堆栈面板不合适)......我只是用手写了这个,记住我过去做过的类似事情。
    • @Timothy Khouri:TextBlock 也不是字符串类型。您将无法在 TextTextBox 属性内使用任何类型的 UIElement
    【解决方案2】:

    编辑

    以下代码将直接选择鼠标下的单词

    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);
        }
    }
    

    【讨论】:

    • 当然可以,很高兴为您提供帮助!我很确定 if 语句中的代码可以用一点 Linq 来缩短:)
    【解决方案3】:

    非常有趣的问题,我不马上知道答案,周围有类似的问题,不是开箱即用的解决方案,但如果你解决它并让它启发你,一个解决方案是可能的:

    Get Displayed Text from TextBlock

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-06
      • 1970-01-01
      相关资源
      最近更新 更多