Reputation: 1995
I am looking for a way to highlight some search terms inside my custom ListView control. I have a bunch of TextBlocks (one for each property of each row). For example the artist name, title and genre of each song.
Now, if someone searches for "Emi" then I want the artist field to show up like <b>Emi</b>nem
, if the value of the binding is Eminem.
I have looked around a bit but didn't get much wiser. I figure I need some combination of a converter and using Inlines (which I've never used before) and/or InlineExpressions (or are those only for ASP?).
All bindings and templates are created on-the-fly in C# and not XAML.
Thanks!
Upvotes: 2
Views: 702
Reputation: 3348
Yes, you are right about using converter(actually it will may be even multiconveter) and Inlines collection of a TextBlock. So let's say you are passing search item(in your case word 'Emi') to the converter. You will also need to manipulate the TextBlock with resulting text somehow. For simplicity let's assume that TextBlock's Tag property(not Text) contails the whole string being searched(word '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(...) {...}
}
Upvotes: 2