需求:通过关键字查找数据,把带有关键字的数据显示出来,同时在结果中高亮显示关键字;
如:在123456,135795,369741,这组数据中输入123,要把123456筛选出来,并高亮其中的123,类似显示成 123456 ;
实现方式:利用TextBlock可以使用Run来组成Text内容的特性实现;
/// <summary>
/// 高亮字体
/// </summary>
public class HighlightTextblock : TextBlock
{
public string DefaultText { get; set; }
public string HiText
{
get { return (string)GetValue(HiTextProperty); }
set { SetValue(HiTextProperty, value); }
}
public static readonly DependencyProperty HiTextProperty =
DependencyProperty.Register("HiText", typeof(string), typeof(HighlightTextblock), new PropertyMetadata(string.Empty, OnHiTextChanged));
private static void OnHiTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
HighlightTextblock block = d as HighlightTextblock;
block.UpdateHighText(e.NewValue.ToString());
}
private void UpdateHighText(string hiText)
{
if (string.IsNullOrEmpty(DefaultText) || DefaultText != Text)
{
DefaultText = Text;
}
if (!string.IsNullOrEmpty(hiText))
{
Text = string.Empty;
string[] spli = DefaultText.Split(new string[] { hiText }, StringSplitOptions.None);
//字符串拆分 用Run拼接 进行高亮展示
for (int i = 0; i < spli.Length; i++)
{
Inlines.Add(new Run(spli[i]));
if (i < spli.Length - 1)
{
int searchstart = Text.Length;
var iCaseTextIndex = DefaultText.IndexOf(hiText, searchstart, StringComparison.OrdinalIgnoreCase);
if (iCaseTextIndex < 0)
{
continue;
}
string caseText = DefaultText.Substring(iCaseTextIndex, hiText.Length);
Inlines.Add(new Run(caseText) { Background = new System.Windows.Media.SolidColorBrush((Color)ColorConverter.ConvertFromString("#E9F566")) });
}
}
}
else
{
Text = DefaultText;
}
}
}
XAML中调用:
<controls:HighlightTextblock HiText="{Binding ElementName=textbox, Path=Text}" Grid.Column="2" Text="{Binding }" Style="{StaticResource TitleTextStyle}" HorizontalAlignment="Center" TextTrimming="WordEllipsis" ToolTip="{Binding}"/>
绑定的HiText是输入框的字符串;
<TextBox Height="40" x:Name="textbox" VerticalContentAlignment="Center" Width="250" HorizontalAlignment="Left" Margin="20 0 0 0">
<i:Interaction.Triggers>
<i:EventTrigger EventName="TextChanged">
<cmd:EventToCommand Command="{Binding TextChangeCommand}" CommandParameter="{Binding ElementName=textbox ,Path=Text}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</TextBox>
我这里做的是上方一个textbox,下方一个ItemsControl,HighlightTextblock控件作为的ItemsControl的ItemTemplate,ItemsControl里展示的内容始终是通过上方textbox筛选后过滤的内容,并通过控件高亮展示,实现效果如下;