2010-12-18 75 views
2

我试图突出一个列表框数据绑定文本和突出字符串匹配完全一样的Windows Phone的电子邮件应用程序7在WP7数据绑定高亮显示文本列表框

搜索按钮拉起一个弹出,并在TextChanged事件,我正在从主列表中筛选并重新设置DataContext:

private void txtSearch_TextChanged(object sender, TextChangedEventArgs e) 
{ 
    results = allContent.Where(
    x => x.Content.Contains(txtSearch.Text) 
).ToList(); 

    DataContext = results; 
} 

该部分工作得很好。问题在于突出显示匹配的文本。我试过在各种事件(Loaded,ItemsChanged)中迭代ListBoxItems,但它们总是空的。

有关如何在数据绑定ListItem的子文本框中完成文本高亮显示的任何想法?

回答

2

这里是我去解决:

private void ResultsText_Loaded(object sender, RoutedEventArgs e) 
{ 
    var textBlock = sender as TextBlock; 
    if (txtSearch.Text.Length > 0 && textBlock.Text.Length > 0) 
    { 
     BoldText(ref textBlock, txtSearch.Text, Color.FromArgb(255, 254, 247, 71)); 
    } 
} 

public static void BoldText(ref TextBlock tb, string partToBold, Color color) 
{ 
    string Text = tb.Text; 
    tb.Inlines.Clear(); 

    Run r = new Run(); 
    r.Text = Text.Substring(0, Text.IndexOf(partToBold)); 
    tb.Inlines.Add(r); 

    r = new Run(); 
    r.Text = partToBold; 
    r.FontWeight = FontWeights.Bold; 
    r.Foreground = new SolidColorBrush(color); 
    tb.Inlines.Add(r); 

    r = new Run(); 
    r.Text = Text.Substring(Text.IndexOf(partToBold) + partToBold.Length, Text.Length - (Text.IndexOf(partToBold) + partToBold.Length)); 
    tb.Inlines.Add(r); 
}