【问题标题】:Is there a way I can highlight specific text in a textbox?有没有办法可以突出显示文本框中的特定文本?
【发布时间】:2014-01-30 19:48:49
【问题描述】:

一个 Windows Phone 问题 C#

我有一个名为“搜索”的TextBox 和另一个名为“内容”的TextBox。如果用户将文本添加到“内容”TextBox,有没有办法使用“搜索”TextBox 来搜索用户在“内容”TextBox 中输入的内容并突出显示该特定文本?

例如当用户想要从手机的应用列表中搜索应用时,它会突出显示该特定应用或包含该文本的任何应用。

如果有人有解决方案 请告诉我:)

【问题讨论】:

标签: c# search windows-phone-8


【解决方案1】:

要在 TextBox 中选择文本,this question 提供了答案,基本上:

//To select all text
textbox.SelectionStart = 0;
textbox.SelectionLength = textbox.Text.Length;

只需应用更多逻辑即可实现您想要的。首先从Content文本框获取输入,在Search文本框的文本中找到这个值的索引。如果值存在(因此索引大于-1),您可以设置SelectionStartSelectionLength

string content = Content.Text;
int index = Search.Text.IndexOf(content);

if(index > -1)
{
    Search.SelectionStart = index;
    Search.SelectionLength = content.Length;
}

更新:

我在 WPF 解决方案中尝试了以下代码,它正常工作,这也适用于 Windows Phone。

  • SearchTextBoxTextBox
  • ContentTextBlock

只要你知道代码中的所有内容:

var regex = new Regex("(" + SearchTextBox.Text + ")", RegexOptions.IgnoreCase);

if (SearchTextBox.Text.Length == 0)
{
    string str = Content.Text;
    Content.Inlines.Clear();
    Content.Inlines.Add(str);
}
else
{
    //get all the words from the 'content'
    string[] substrings = regex.Split(Content.Text);
    Content.Inlines.Clear();

    foreach (var item in substrings)
    {
        //if a word from the content matches the search-term
        if (regex.Match(item).Success)
        {
            //create a 'Run' and add it to the TextBlock
            Run run = new Run(item);
            run.Foreground = Brushes.Red;
            Content.Inlines.Add(run);
        }
        else //if no match, just add the text again
            Content.Inlines.Add(item);
    }
}

【讨论】:

  • 嘿阿巴斯,谢谢你,但我似乎无法让它工作。我尝试将它添加到按钮单击事件中,但实际上没有任何反应,甚至尝试添加一个 focus() 方法来聚焦文本框,然后进行选择,但仍然没有用。有什么想法吗?
  • 请检查我编辑的答案以获取另一种方法。 :)
  • 谢谢!我从这里得到的。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-01-23
  • 1970-01-01
  • 2014-08-15
  • 1970-01-01
  • 1970-01-01
  • 2011-04-30
  • 1970-01-01
相关资源
最近更新 更多