我正在寻找一种方法来突出显示自定义 ListView 控件中的某些搜索词。我有一堆 TextBlock(每行的每个属性一个)。例如每首歌曲的艺术家姓名、标题和流派。
现在,如果有人搜索“Emi”,那么我希望艺术家字段显示为 <b>Emi</b>nem
,如果绑定(bind)的值为 Eminem。
我环顾四周,但并没有变得更加明智。我想我需要转换器和使用 Inlines(我以前从未使用过)和/或 InlineExpressions(或者那些仅适用于 ASP?)的某种组合。
所有绑定(bind)和模板都是在 C# 中即时创建的,而不是 XAML。
谢谢!
最佳答案
是的,您关于使用转换器(实际上它甚至可能是多转换器)和 TextBlock 的内联集合是正确的。 假设您正在将搜索项(在您的例子中为“Emi”)传递给转换器。您还需要以某种方式使用结果文本来操作 TextBlock。为了简单起见,我们假设 TextBlock 的 Tag 属性(不是 Text)包含正在搜索的整个字符串(单词“Eminem”)。
class HighlightPartOfTextConverter : IValueConverter {
public object Convert(object value/*this is TextBlock*/, Type type, object parameter/*this is 'Emi'*/, CultureInfo ci){
var textBlock = value as TextBlock;
string str = textBlock.Tag as string;
string searchThis = parameter as string;
int index = str.IndexOf(searchThis);
if(index >= 0){
string before = str.Substring(0, index);
string after = str.Substring(index + searchThis.Length);
textBlock.Inlines.Clear();
textBlock.Inlines.Add(new Run(){Text=before});
textBlock.Inlines.Add(new Run(){Text=searchThis, FontWeight = FontWeights.Bold});
textBlock.Inlines.Add(new Run(){Text=after});
}
return "";
}
public object ConvertBack(...) {...}
}
关于c# - WPF:将 TextBlock 的绑定(bind)值的一部分加粗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17131182/