您的位置:首页 > 其它

WPF搜索关键字高亮显示

2015-01-15 15:11 344 查看
目标:在WPF中,对lucene.net进行全文检索后的结果中包含的关键字进行高亮显示。

检索结果中的关键字高亮显示,在网页中显示是很简单的,lucene中加标签样式就可以了,可是在WPF中就不行了。

我在WPF中用GridControl显示搜索结果列表,GridControl的模板里用TextBlock显示文字。

写了2个方法来使TextBlock中的文字高亮。

1、查找GridControl中的所有TextBlock

public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}

foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}

2、遍历每个TextBlock,并高亮显示其包含的关键字。如果有多个关键字,各关键字以空格分隔。

void HighlighterKeyWords(string keyWords, DependencyObject depObj)
{
if (String.IsNullOrEmpty(keyWords))
return;
string[] arr = keyWords.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

StringBuilder pattern = new StringBuilder();
foreach (string item in arr)
{
pattern.AppendFormat("({0})+|", item);
}
Regex regex = new Regex(pattern.ToString().TrimEnd('|'), RegexOptions.IgnoreCase);
System.Threading.Thread.Sleep(10);
this.Dispatcher.BeginInvoke(new Action(() =>
{
IEnumerable<TextBlock> tbList = FindVisualChildren<TextBlock>(depObj);
foreach (TextBlock tb in tbList)
{
string[] substrings = regex.Split(tb.Text);
tb.Inlines.Clear();
foreach (var item in substrings)
{
if (regex.Match(item).Success)
{
Run runx = new Run(item);
runx.Background = Brushes.Red;
tb.Inlines.Add(runx);
}
else
{
tb.Inlines.Add(item);
}
}
}
}));

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: