Windows Phone问题C#
我有一个TextBox
名为“搜索”和另一个TextBox
名为“内容”。如果用户将文本添加到“内容”中TextBox
,是否可以使用“搜索”TextBox
来搜索用户在“内容”中键入的内容TextBox
并突出显示该特定文本?
例如,当用户想要从手机的“应用程序列表”中搜索某个应用程序时,它将突出显示并显示该特定应用程序或包含该文本的任何应用程序。
如果有人有解决方案,请告诉我:)
要选择TextBox中的文本,此问题基本上提供了答案:
//To select all text
textbox.SelectionStart = 0;
textbox.SelectionLength = textbox.Text.Length;
只有更多的逻辑可以应用来实现您想要的。首先从Content
文本框中获取输入,然后在文本框中的文本中找到该值的索引Search
。如果该值存在(因此索引大于-1),则可以设置SelectionStart
和SelectionLength
。
string content = Content.Text;
int index = Search.Text.IndexOf(content);
if(index > -1)
{
Search.SelectionStart = index;
Search.SelectionLength = content.Length;
}
我尝试在WPF解决方案中遵循以下代码,因此它可以正常工作,因此对于Windows Phone也应如此。
SearchTextBox
是一个 TextBox
Content
是一个 TextBlock
只是您知道代码中的所有内容:
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);
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句