public class StringToHighlightConverter : IValueConverter
{ public object Convert(object values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{ //get the data found in the text
string dataText = (string)values;
if (!string.IsNullOrEmpty(dataText) && !string.IsNullOrEmpty(TextSearchFilter.SearchClause))
{ List<StringOccurance> highlightedWords = new List<StringOccurance>();
foreach(string token in TextSearchFilter.TokenizedSearchClause)
{ highlightedWords.AddRange(StringEx.FindStringOccurances(dataText, token));
}
if (highlightedWords.Count == 0)
return CreateTextBlock(dataText);
int textStartIdx = 0;
string plainWord = string.Empty;
int wordOccuranceIdx = 0; //keep count of the words we have proccessed
Span phrase = new Span();
for (int i = textStartIdx; i < dataText.Length; i++)
{ if (wordOccuranceIdx == highlightedWords.Count)
{ //We have reached the maximum word occurances, add the plain word span
Span wordSpan = CreateWordSpan(dataText.Substring(i), false);
phrase.Inlines.Add(wordSpan);
break;
}
//get the currrent word that needs to be highlighted
StringOccurance wordOccurance = highlightedWords[wordOccuranceIdx];
if (wordOccurance.StartIndex == i)
{ //add the plain word span
if (!string.IsNullOrEmpty(plainWord))
{ Span wordSpan = CreateWordSpan(plainWord, false);
plainWord = string.Empty;
phrase.Inlines.Add(wordSpan);
}
Span highLightedWordSpan = CreateWordSpan(wordOccurance.Value, true);
wordOccuranceIdx++;
//issue with this
i = i + (wordOccurance.Value.Length - 1);
phrase.Inlines.Add(highLightedWordSpan);
continue;
}
if (i >= dataText.Length)
{ //add the plain word span
//Span wordSpan = CreateWordSpan(dataText.Substring(i), false);
Span wordSpan = CreateWordSpan(plainWord, false);
phrase.Inlines.Add(wordSpan);
break;
}
plainWord = plainWord + dataText[i];
}
return CreateTextBlock(phrase);
}
return CreateTextBlock(dataText);
}
private TextBlock CreateTextBlock(Inline text)
{ TextBlock block = new TextBlock(text);
block.TextWrapping = System.Windows.TextWrapping.Wrap;
return block;
}
private TextBlock CreateTextBlock(string text)
{ Span textSpan = new Span();
textSpan.Inlines.Add(text);
return CreateTextBlock(textSpan);
}
private Span CreateWordSpan(string text, bool highlight)
{
Span wordSpan = new Span();
if( highlight == true)
{ wordSpan.Background = Brushes.Yellow;
}
wordSpan.Inlines.Add(text);
return wordSpan;
}
public object ConvertBack(object value, Type targetTypes, object parameter, System.Globalization.CultureInfo culture)
{ throw new NotSupportedException("Not supported"); }
}