有没有办法可以突出显示文本框中的特定文本?

时间:2014-01-29 11:26:58

标签: c# search windows-phone-8

Windows Phone问题 C#

我有一个名为“搜索”的TextBox和另一个名为“内容”的TextBox。如果用户在“内容”TextBox中添加了文字,是否有办法,使用“搜索”TextBox搜索用户在“内容”TextBox中输入的内容并突出显示具体文字?

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

enter image description here

如果有人有解决方案 请让我知道:))

1 个答案:

答案 0 :(得分:2)

要选择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);
    }
}
相关问题