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 要高亮的部分,例如搜索框的内容}"/>
相关推荐
★YUI★2 小时前
学习游戏制作记录(克隆技能)7.25
学习·游戏·unity·c#
坚持吧20214 小时前
【无标题】word 中的中文排序
开发语言·c#
_oP_i4 小时前
c# openxml 打开加密 的word读取内容
开发语言·c#·word
醉酒的李白、5 小时前
C#观察者模式示例代码
观察者模式·c#
百锦再8 小时前
WPF依赖属性深度解析:从原理到高级应用
wpf·依赖·绑定·验证·net·强制
✎ ﹏梦醒͜ღ҉繁华落℘10 小时前
WPF高级学习(一)
学习·wpf
界面开发小八哥10 小时前
界面控件DevExpress WPF v25.1新版亮点:模板库更新升级
ui·.net·wpf·界面控件·devexpress·ui开发
咩咩觉主13 小时前
Unity编辑器拓展 IMGUI与部分Utility知识总结(代码+思维导图)
unity·c#·编辑器·游戏引擎
△曉風殘月〆14 小时前
WPF MVVM进阶系列教程(二、数据验证)
wpf·mvvm
无规则ai14 小时前
C#入门实战:数字计算与条件判断
c#·visual studio