WPF TextBlock 根据搜索条件突出显示某些部分

作者:编程家 分类: swift 时间:2025-08-16

WPF TextBlock 根据搜索条件突出显示某些部分

WPF(Windows Presentation Foundation)是一种用于构建 Windows 客户端应用程序的技术。其中的 TextBlock 控件是用于显示文本的基本控件之一。在某些情况下,我们可能需要根据搜索条件来突出显示文本中的某些部分,以提高用户体验。本文将介绍如何使用 WPF 的 TextBlock 控件来实现这一功能,并提供相应的案例代码。

案例代码

下面是一个示例代码,演示了如何使用 WPF 的 TextBlock 控件来根据搜索条件突出显示文本中的某些部分:

xaml

xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

Title="TextBlock Highlighting Example" Height="450" Width="800">

csharp

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Media;

namespace TextBlockHighlightingExample

{

public partial class MainWindow : Window

{

public MainWindow()

{

InitializeComponent();

}

private void searchTextBox_TextChanged(object sender, TextChangedEventArgs e)

{

string searchText = searchTextBox.Text;

if (!string.IsNullOrEmpty(searchText))

{

string text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed dapibus dolor at dui maximus, non luctus nisi ultricies. Mauris auctor orci non nunc iaculis, eu tempor mi convallis. Nulla facilisi. Sed at commodo magna. Vivamus suscipit commodo fermentum. Suspendisse non leo id metus tempor ultricies. Duis id ultrices ligula, at tristique metus. Nam vitae nisi nec nulla sagittis pellentesque.";

textBlock.Inlines.Clear();

int index = text.IndexOf(searchText);

int lastIndex = 0;

while (index != -1)

{

textBlock.Inlines.Add(text.Substring(lastIndex, index - lastIndex));

Run highlightRun = new Run(text.Substring(index, searchText.Length));

highlightRun.Background = Brushes.Yellow;

textBlock.Inlines.Add(highlightRun);

lastIndex = index + searchText.Length;

index = text.IndexOf(searchText, lastIndex);

}

textBlock.Inlines.Add(text.Substring(lastIndex));

}

else

{

textBlock.Text = string.Empty;

}

}

}

}

实现步骤

1. 首先,在 XAML 文件中创建一个 TextBlock 控件和一个 TextBox 控件,分别用于显示文本和接收搜索条件的输入。

2. 在 TextBlock 控件的 TextChanged 事件处理程序中,获取搜索条件的文本。

3. 检查搜索条件是否为空,如果不为空,则获取要显示的文本。

4. 使用 TextBlock 控件的 Inlines 属性来逐个添加文本和突出显示的部分。

5. 在找到搜索条件的位置时,创建一个 Run 对象,并设置其 Background 属性为黄色,以突出显示该部分文本。

6. 添加完所有文本和突出显示的部分后,更新 TextBlock 控件的内容。

通过使用 WPF 的 TextBlock 控件,我们可以根据搜索条件来突出显示文本中的某些部分。这种方式可以提高用户体验,使用户更容易找到他们感兴趣的内容。希望本文的案例代码能对你理解和使用 WPF TextBlock 控件有所帮助。