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 要高亮的部分,例如搜索框的内容}"/>
相关推荐
xcLeigh1 小时前
WPF跨平台开发探讨:借助相关技术实现多平台应用
c#·wpf
月巴月巴白勺合鸟月半5 小时前
工作记录 2017-02-03
前端·c#·健康医疗
我要打打代码6 小时前
C#进阶(多线程相关)
开发语言·c#
PfCoder10 小时前
C# 事件(Event)核心概念
开发语言·c#
PfCoder10 小时前
C# 中泛型(Generics)‌的核心概念
开发语言·windows·c#
CS软件开发框架12 小时前
.NET Winform桌面应用程序禁用dpi缩放
c#·.net·.netcore·visual studio
Damon小智13 小时前
C#进阶-ASP.NET网站会话固定漏洞的解决
网络安全·c#·asp.net·漏洞修复·会话固定
埃菲尔铁塔_CV算法16 小时前
WPF 开发从入门到进阶(五)
深度学习·算法·机器学习·计算机视觉·wpf
咩咩觉主17 小时前
C# &Unity 唐老狮 No.10 模拟面试题
开发语言·unity·c#
初级代码游戏17 小时前
VSTO(C#)Excel开发 系列目录 含源码发布
c#·excel·源码·vba·vsto