You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在AutoSuggestBox中加粗匹配的搜索字符串?

兄弟,我完全懂你这种想实现个小功能却搜不到方案的憋屈!AutoSuggestBox确实没内置高亮匹配文本的功能,不过咱们可以通过自定义下拉项模板+值转换器轻松搞定,给你一步步拆解:

核心思路

本质是把下拉项的文本拆分成「匹配关键词」和「普通文本」两部分,给匹配部分套上加粗样式。我们用IMultiValueConverter来处理文本拆分逻辑,再通过ItemTemplate把处理后的富文本渲染出来。

步骤1:实现高亮文本转换器

这个转换器会接收两个参数:下拉项的原始文本,以及AutoSuggestBox当前输入的搜索关键词,然后返回带有加粗匹配段的文本集合。

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Data;

public class HighlightTextConverter : IMultiValueConverter
{
    public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
    {
        // 校验输入参数合法性
        if (values.Length < 2 || values[0] is not string itemText || values[1] is not string searchKeyword)
            return new Run(itemText ?? string.Empty);

        var inlineCollection = new InlineCollection();
        string lowerItemText = itemText.ToLower();
        string lowerSearchKeyword = searchKeyword.ToLower();

        int currentPosition = 0;
        int matchPosition;

        // 循环查找所有匹配的关键词位置
        while ((matchPosition = lowerItemText.IndexOf(lowerSearchKeyword, currentPosition)) != -1)
        {
            // 添加匹配前的普通文本
            if (matchPosition > currentPosition)
                inlineCollection.Add(new Run(itemText.Substring(currentPosition, matchPosition - currentPosition)));

            // 添加加粗的匹配文本
            inlineCollection.Add(new Run(itemText.Substring(matchPosition, lowerSearchKeyword.Length)) 
            { 
                FontWeight = FontWeights.Bold,
                Foreground = Brushes.DarkBlue // 还可以顺便改个颜色增强高亮
            });

            currentPosition = matchPosition + lowerSearchKeyword.Length;
        }

        // 添加剩余的普通文本
        if (currentPosition < itemText.Length)
            inlineCollection.Add(new Run(itemText.Substring(currentPosition)));

        return inlineCollection;
    }

    public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
    {
        // 不需要反向转换,直接抛异常
        throw new NotImplementedException("反向转换未实现");
    }
}

步骤2:配置AutoSuggestBox的ItemTemplate

在XAML里声明转换器,然后给AutoSuggestBox指定自定义的下拉项模板,把转换器绑定到TextBlock的Inlines属性上:

<!-- 在Window/UserControl的资源里声明转换器 -->
<Window.Resources>
    <local:HighlightTextConverter x:Key="HighlightTextConverter"/>
</Window.Resources>

<!-- 你的AutoSuggestBox -->
<AutoSuggestBox x:Name="MyAutoSuggestBox"
                PlaceholderText="输入关键词搜索..."
                QueryIcon="Find">
    <AutoSuggestBox.ItemTemplate>
        <DataTemplate>
            <!-- 用TextBlock承载富文本 -->
            <TextBlock Padding="4,2">
                <TextBlock.Inlines>
                    <MultiBinding Converter="{StaticResource HighlightTextConverter}">
                        <!-- 绑定下拉项的文本内容,如果是自定义对象就改成对应的属性,比如Path="UserName" -->
                        <Binding Path="."/>
                        <!-- 绑定AutoSuggestBox当前的输入文本 -->
                        <Binding ElementName="MyAutoSuggestBox" Path="Text"/>
                    </MultiBinding>
                </TextBlock.Inlines>
            </TextBlock>
        </DataTemplate>
    </AutoSuggestBox.ItemTemplate>
</AutoSuggestBox>

额外优化提示

  • 如果需要区分大小写匹配,把代码里的ToLower()去掉就行;
  • 如果要实现全词匹配,可以在查找匹配位置时,额外判断匹配段的前后是否是单词边界(比如空格、标点);
  • 如果你用的是UWP平台,代码逻辑完全一致,只需要把命名空间换成Windows.UI.Xaml相关的就行。

内容的提问来源于stack exchange,提问作者John Eddy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:14:19