WPF实现搜索文本高亮

WPF实现搜索文本高亮

1、使用自定义的TextBlock

csharp 复制代码
    public class HighlightTextblock : TextBlock
    {
        public string DefaultText { get; set; }

        public string HiText
        {
            get { return (string)GetValue(HiTextProperty); }
            set { SetValue(HiTextProperty, value); }
        }

        // Using a DependencyProperty as the backing store for HiText.  This enables animation, styling, binding, etc...
        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 = Regex.Split(DefaultText, hiText, RegexOptions.IgnoreCase);
                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 = Brushes.Yellow });
                    }
                }
            }
            else
            {
                Text = DefaultText;
            }
        }
    }

2、界面中引用上述自定义控件

csharp 复制代码
xmlns:local="clr-namespace:命名空间;assembly=包名"

3、使用高亮控件

csharp 复制代码
<local:HighlightTextblock   Text="{Binding 完整文本}" HiText="{Binding 要高亮的部分,例如搜索框的内容}"/>
相关推荐
red-fly3 分钟前
c#修改ComboBox当前选中项的文本
c#·combobox
wangnaisheng31 分钟前
【WPF】Opacity 属性的使用
wpf
bicijinlian3 小时前
.Net HttpClient 概述
c#·.net·httpclient·.net httpclient
码观天工4 小时前
.NET 原生驾驭 AI 新基建实战系列(七):Weaviate ── 语义搜索的智能引擎创新者
ai·c#·.net·向量数据库·weaviate
Zhen (Evan) Wang5 小时前
.NET 8 + Angular WebSocket 高并发性能优化
c#·.net·angular
chenyuhao20245 小时前
链表面试题7之相交链表
数据结构·算法·链表·面试·c#
姬激薄5 小时前
配置Hadoop集群-集群配置
wpf
python算法(魔法师版)6 小时前
.NET 在鸿蒙系统上的适配现状
华为od·华为·华为云·.net·wpf·harmonyos
菜鸟分享录6 小时前
MCP 入门实战:用 C# 开启 AI 新篇章
ai·c#·semantic kernel·mcp
编程乐趣7 小时前
一个用C#开发的记事本Notepads开源编辑器
c#·编辑器·.net