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 要高亮的部分,例如搜索框的内容}"/>
相关推荐
张鱼小丸子_微辣2 小时前
.Net Framework 4/C# 集合和索引器
c#
布伦鸽2 小时前
C# WPF 左右布局实现学习笔记(1)
笔记·学习·c#·wpf
InCerry3 小时前
C# 模式匹配全解:原理、用法与易错点
c#
IGP94 小时前
20250606-C#知识:List排序
c#·list
老刘忙Giser4 小时前
c# List<string>.Add(s) 报错:UnsupportedOperationException
开发语言·c#
The Future is mine5 小时前
在.NET Core控制器中获取AJAX传递的Body参数
c#·.netcore
Eiceblue6 小时前
C# 快速检测 PDF 是否加密,并验证正确密码
开发语言·pdf·c#·visual studio
FL16238631296 小时前
C#报错 iText.Kernel.Exceptions.PdfException: ‘Unknown PdfException
开发语言·c#
绿荫阿广16 小时前
互联网不景气了那就玩玩嵌入式吧,用纯.NET开发并制作一个智能桌面机器人(五):使用.NET为树莓派开发Wifi配网功能
c#·.net
ou.cs19 小时前
c# :this() 和 :base()区别
开发语言·c#