当前位置: 首页 > news >正文

WPF实现搜索文本高亮

WPF实现搜索文本高亮

1、使用自定义的TextBlock

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、界面中引用上述自定义控件

xmlns:local="clr-namespace:命名空间;assembly=包名"

3、使用高亮控件

<local:HighlightTextblock   Text="{Binding 完整文本}" HiText="{Binding 要高亮的部分,例如搜索框的内容}"/>
http://www.lryc.cn/news/356731.html

相关文章:

  • Vue小程序项目知识积累(三)
  • React Native 之 像素比例(十七)
  • Leetcode 112:路径总和
  • 电源模块测试系统怎么测试输入电压范围?
  • 实战指南:Vue 2基座 + Vue 3 + Vite + TypeScript微前端架构实现动态菜单与登录共享
  • Java面试进阶指南:高级知识点问答精粹(一)
  • 儿童礼物笔记
  • LeetCode215数组中第K个最大元素
  • LeetCode //C - 143. Reorder List
  • 速盾:cdn如何解析?
  • K8s集群调度续章
  • 大工作量LUAD代谢重编程模型多组学(J Transl Med)
  • C语言#include<>和#include““有什么区别?
  • 正在直播:Microsoft Copilot Studio 新增支持Copilot代理、Copilot扩展等多项功能
  • 数据通信基本概念汇总
  • AcWing 835. Trie字符串统计——算法基础课题解
  • RT-DETR算法改进【NO.1】借鉴CVPR2024中的StarNet网络StarBlock改进算法
  • 5,串口编程---实现简单的用串口发送接收数据
  • LeetCode583:两个字符串的删除操作
  • LLama学习记录
  • 如何克隆非默认分支
  • 数据结构——图
  • 蓝桥杯—SysTick中断精准定时实现闪烁灯
  • ML307R OpenCPU UDP使用
  • pod详解
  • 免费插件集-illustrator插件-Ai插件-文本对象分行
  • web学习笔记(五十九)
  • UE5 UE4 快速定位节点位置
  • go routing 之 gorilla/mux
  • 新火种AI|警钟长鸣!教唆自杀,威胁人类,破坏生态,AI的“反攻”值得深思...