我通过创建一个自定义控件来实现这一点 -HighlightableTextBlock
它继承TextBlock
并添加了以下依赖属性:
public string HighlightSource
{
get { return (string)GetValue(HighlightSourceProperty); }
set { SetValue(HighlightSourceProperty, value); }
}
public static readonly DependencyProperty HighlightSourceProperty =
DependencyProperty.Register("HighlightSource", typeof(string), typeof(HighlightableTextBlock), new PropertyMetadata("", OnChange));
OnChange
在事件处理程序中执行实际突出显示:
static void OnChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var textBlock = d as HighlightableTextBlock;
var text = textBlock.Text;
var source = textBlock.HighlightSource;
if (!string.IsNullOrWhiteSpace(source) && !string.IsNullOrWhiteSpace(text))
{
var index = text.IndexOf(source);
if (index >= 0)
{
var start = text.Substring(0, index);
var match = text.Substring(index, source.Length);
var end = text.Substring(index + source.Length);
textBlock.Inlines.Clear();
textBlock.Inlines.Add(new Run(start));
textBlock.Inlines.Add(new Run(match) { Foreground = Brushes.Red });
textBlock.Inlines.Add(new Run(end));
}
}
}
事物的标记方面如下所示:
<controls:HighlightableTextBlock Text="{Binding SomeText}"
HighlightSource="{Binding ElementName=SearchTextBox, Path=Text}">
</controls:HighlightableTextBlock>
似乎为我工作。在这个例子中,我已经硬编码了匹配子字符串的颜色,但是如果你想从标记中传递它,你可以添加一个单独的属性。
希望这可以帮助...