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 要高亮的部分,例如搜索框的内容}"/>
相关推荐
gu2023 分钟前
c#编程:学习Linq,重几个简单示例开始
开发语言·学习·c#·linq
pchmi5 小时前
CNN常用卷积核
深度学习·神经网络·机器学习·cnn·c#
yuanpan5 小时前
23种设计模式之《组合模式(Composite)》在c#中的应用及理解
开发语言·设计模式·c#·组合模式
滴_咕噜咕噜6 小时前
C#基础总结:常用的数据结构
开发语言·数据结构·c#
万兴丶9 小时前
Unity 适用于单机游戏的红点系统(前缀树 | 数据结构 | 设计模式 | 算法 | 含源码)
数据结构·unity·设计模式·c#
程序猿多布11 小时前
C#设计模式 学习笔记
设计模式·c#
软件黑马王子17 小时前
Unity游戏制作中的C#基础(5)条件语句和循环语句知识点全解析
游戏·unity·c#
shepherd枸杞泡茶17 小时前
第3章 3.3日志 .NET Core日志 NLog使用教程
c#·asp.net·.net·.netcore
界面开发小八哥20 小时前
界面组件DevExpress WPF中文教程:Grid - 如何显示和隐藏列?
wpf·界面控件·devexpress·ui开发·.net9
虚假程序设计21 小时前
python用 PythonNet 从 Python 调用 WPF 类库 UI 用XAML
python·ui·wpf