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 要高亮的部分,例如搜索框的内容}"/>
相关推荐
攻城狮CSU1 小时前
WPF中核心接口 INotifyPropertyChanged
wpf
c#上位机1 小时前
wpf之Interaction.Triggers
c#·wpf
是木子啦5 小时前
wpf passwordbox控件 光标移到最后
c#·wpf
The Sheep 20235 小时前
wpf 命令理解
wpf
布伦鸽5 小时前
C# WPF DataGrid使用Observable<Observable<object>类型作为数据源
开发语言·c#·wpf
.NET修仙日记6 小时前
2025年ASP.NETMVC面试题库全解析
面试·职场和发展·c#·asp.net·mvc·面试题·asp.net mvc
weixin_456904277 小时前
C# 串口通信完整教程 (.NET Framework 4.0)
网络·c#·.net
我笔记8 小时前
.net过滤器和缓存
c#
夏子曦17 小时前
C#内存管理深度解析:从栈堆原理到高性能编程实践
开发语言·c#
分布式存储与RustFS17 小时前
告别复杂配置:用Milvus、RustFS和Vibe Coding,60分钟DIY专属Chatbot
wpf·文件系统·milvus·对象存储·minio·rustfs·vibe