如何突出显示列表框内匹配的子字符串? [英] How to highlight matching sub-strings inside a ListBox?

查看:81
本文介绍了如何突出显示列表框内匹配的子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本框和一个列表框,用于搜索一组数据.在列表框内搜索文本时,如果在列表中的任何位置都找到匹配的字符串,则该文本应以绿色加粗显示.

I have one TextBox and one listbox for searching a collection of data. While searching a text inside a Listbox if that matching string is found anywhere in the list it should show in Green color with Bold.

例如我有像这样的字符串集合 依赖项属性,自定义属性,普通属性".如果在搜索文本框中输入"prop",则所有带有"prop"的三个(仅单词Prop)应为粗体,其颜色应为绿色.任何想法如何做到这一点?

eg. I have string collection like "Dependency Property, Custom Property, Normal Property". If I type in the Search Text box "prop" all the Three with "prop" (only the word Prop) should be in Bold and its color should be in green. Any idea how it can be done?.

列表框内的数据使用DataTemplate表示.

Data inside listbox is represented using DataTemplate.

推荐答案

我已经创建了HighlightTextBehavior,可以将其附加到列表项模板内的TextBlock上(您需要添加对System.Windows.Interactivity的引用到您的项目中).您可以将行为绑定到包含要突出显示的文本的属性,其余的将完成.

I've created a HighlightTextBehavior that you can attach to a TextBlock within your list item templates (you'll need to add a reference to System.Windows.Interactivity to your project). You bind the behavior to a property containing the text you want to highlight, and it does the rest.

目前,它仅突出显示字符串的第一个实例.它还假定没有其他格式应用于文本.

At the moment, it only highlights the first instance of the string. It also assumes that there is no other formatting applied to the text.

using System.Linq;
using System.Text;
using System.Windows.Interactivity;
using System.Windows.Controls;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Media;

namespace StringHighlight
{
    public class HighlightTextBehavior : Behavior<TextBlock>
    {
        public string HighlightedText
        {
            get { return (string)GetValue(HighlightedTextProperty); }
            set { SetValue(HighlightedTextProperty, value); }
        }

        // Using a DependencyProperty as the backing store for HighlightedText.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty HighlightedTextProperty =
            DependencyProperty.Register("HighlightedText", typeof(string), typeof(HighlightTextBehavior), new UIPropertyMetadata(string.Empty, HandlePropertyChanged));

        private static void HandlePropertyChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
        {
            (sender as HighlightTextBehavior).HandlePropertyChanged();
        }

        private void HandlePropertyChanged()
        {
            if (AssociatedObject == null)
            {
                return;
            }

            var allText = GetCompleteText();

            AssociatedObject.Inlines.Clear();

            var indexOfHighlightString = allText.IndexOf(HighlightedText);

            if (indexOfHighlightString < 0)
            {
                AssociatedObject.Inlines.Add(allText);
            }
            else
            {
                AssociatedObject.Inlines.Add(allText.Substring(0, indexOfHighlightString));
                AssociatedObject.Inlines.Add(new Run() { 
                    Text = allText.Substring(indexOfHighlightString, HighlightedText.Length), 
                    Foreground = Brushes.Green,
                    FontWeight = FontWeights.Bold });
                AssociatedObject.Inlines.Add(allText.Substring(indexOfHighlightString + HighlightedText.Length));
            }
        }

        private string GetCompleteText()
        {
            var allText = AssociatedObject.Inlines.OfType<Run>().Aggregate(new StringBuilder(), (sb, run) => sb.Append(run.Text), sb => sb.ToString());
            return allText;
        }
    }
}

以下是使用方式的示例:

Here's an example of how you use it:

    <Window x:Class="StringHighlight.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
        xmlns:b="clr-namespace:StringHighlight"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Grid.Resources>
            <x:Array x:Key="MyStrings" Type="{x:Type sys:String}">
                <sys:String>This is my first string</sys:String>
                <sys:String>Another string</sys:String>
                <sys:String>A third string, equally imaginative</sys:String>
            </x:Array>
        </Grid.Resources>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBox x:Name="SearchText"/>

        <ListBox Grid.Row="1" ItemsSource="{StaticResource MyStrings}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <TextBlock Grid.Row="1" Text="{Binding}">
                        <i:Interaction.Behaviors>
                            <b:HighlightTextBehavior HighlightedText="{Binding ElementName=SearchText, Path=Text}"/>
                        </i:Interaction.Behaviors>
                    </TextBlock>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>
    </Grid>
</Window>

这篇关于如何突出显示列表框内匹配的子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆