Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

Highlight Searched Text in WPF ListView

, 20 Aug 2010
Rate this:
Please Sign up or sign in to vote.
Solution for highlighting searched text in WPF ListView
HighLighting_Text.PNG

Introduction

I wrote this as an inspiration for how to search in Microsoft Outlook. Imagine that you have a ListView in a WPF application and you are looking for a text in the individual items. It would be useful to highlight the text. The code used in this demo can be adjusted wherever it's appropriate and the highlighted text is displayed by using the TextBox control.

Background

It is assumed you have basic knowledge of C# and WPF. This application is used instead of Text property in TextBlock control, Inline property and class Run through which we can change the text properties (such as Foreground, Background, FontSize, etc.) .

Using the Code

Create a Listview and TextBlock search. Add a TextBox TextChanged event for an instant search in ListView.

<DockPanel LastChildFill="True">      
  <StackPanel  HorizontalAlignment="Left" DockPanel.Dock="Top">           
              <Label Name="labelSearch" Content="Search"/>  
              <TextBox Name="textboxsearch" Width="309" 
			TextChanged="textboxsearch_TextChanged"
                >            
              </TextBox>
 </StackPanel> 
       <ListView Name="listview" Width="310" DockPanel.Dock="Top" 
	HorizontalAlignment="Left" FontWeight="Bold" FontSize="16" AlternationCount="2"
       	ItemContainerStyle="{StaticResource AlternateItemStyle}">
            <ListView.View>          
          <GridView>     
           <GridViewColumn Header="First Name" 
		DisplayMemberBinding="{Binding Path=FirstName}">
           </GridViewColumn>     
           <GridViewColumn Header="Last Name" 
		DisplayMemberBinding="{Binding Path=LastName}">
           </GridViewColumn
          </GridView>    
        </ListView.View>
        </ListView>
    </DockPanel> 

Use TextChanged event to find all the items in ListViewItem with the recursive method FindListViewItem. GetChildrenCount with VisualTreeHelper class will bring the number children object.

 private void textboxsearch_TextChanged(object sender, TextChangedEventArgs e)
        { 
            {
                FindListViewItem(listview);
            }
        }
        public void FindListViewItem(DependencyObject obj)
        {
            for (int i = 0; i < VisualTreeHelper.GetChildrenCount(obj); i++)
            {
                ListViewItem lv = obj as ListViewItem;
                if (lv != null)
                {
                   HighlightText(lv);
                }
                FindListViewItem(VisualTreeHelper.GetChild(obj as DependencyObject, i));
            }
        }
... 

And if DependecyObject type is ListViewItem, use a recursive method HighlightText which looks in ListViewItem for TextBlock objects.

private void HighlightText(Object itx)
        {
            if (itx != null)
            {
                if (itx is TextBlock)
                {
                   ..
                    }
                        else
                        {
                          ...
                        }
                    }
                    return;
                }
                else
                { 
                   ...
                }
            }
        }

If the object is TextBlock type, create a new instance RegEx.

(Parameter RegExOptions.IgnoreCase ignores uppercase and lowercase letters.)

Inserting brackets, you will reach the division of text into the field, which will include the searched text.

 regex = new Regex("(" + textboxsearch.Text + ")", RegexOptions.IgnoreCase);

The text in the TextBlock divides it into a string array of assistance RegEx.Split. Clear the original text with Inlines.Clear.

tb.Inlines.Clear(); 

And again in the foreach cycle, create the text that compares the expression of the field with the search terms with RegEx.Match.

foreach (var item in substrings)  
{
if (regex.Match(item).Success)
…

If identical, then use the Run class, create new Inline element, add text, change the background color, and add text to TextBlock with Inlines.Add methods. Otherwise, just add text.

Run runx = new Run(item);

runx.Background = Brushes.Red;

tb.Inlines.Add(item);

The code to change text in the background in full:

foreach (var item in substrings)
                    {
                        if (regex.Match(item).Success)
                        {
                            Run runx = new Run(item);
                            runx.Background = Brushes.Red;
                            tb.Inlines.Add(runx);
                        }
                        else
                        {
                            tb.Inlines.Add(item);
                        }
                    }

Now we can start the project and try searching.

Conclusion

This application does not create any special effects when you highlight the text, but I think it can serve as an inspiration.

I hope you found it useful and thanks for reading.

History

  • 20th August, 2010: Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Jan Vilášek
Software Developer student
Czech Republic Czech Republic
No Biography provided

Comments and Discussions

 
QuestionOptimizations [modified] PinmemberFocusedWolf22-Jun-12 6:55 
AnswerA full rewrite ;P [modified] PinmemberFocusedWolf22-Jun-12 11:03 
Questionworks well for small documents, but how can i speed it up? PinmemberI_Need_Help20-Dec-11 6:31 
GeneralListview Contents truncated and reordered Pinmembermuthuprakash25-Apr-11 0:53 
GeneralRe: Listview Contents truncated and reordered PinmemberJan Vilášek7-May-11 4:23 
GeneralThank You Pinmembermuthuprakash21-Apr-11 23:25 
GeneralRe: Thank You [modified] PinmemberJan Vilášek22-Apr-11 5:54 
GeneralRe: Thank You Pinmembermuthuprakash22-Apr-11 21:01 
GeneralListView Not highlighted fully Pinmembermuthuprakash21-Apr-11 23:24 
GeneralRe: ListView Not highlighted fully PinmemberMember 834570123-Mar-12 8:47 
GeneralVery good code! PinmemberMember 155142626-Nov-10 10:43 
GeneralRe: Very good code! PinmemberJan Vilášek27-Nov-10 0:26 
GeneralRe: Very good code! PinmemberMember 155142628-Nov-10 20:43 
GeneralRe: Very good code! PinmemberJan Vilášek29-Nov-10 4:38 
GeneralCool!! PinmemberDnGutierrez21-Sep-10 11:06 
GeneralMy vote of 5 PinmemberDnGutierrez21-Sep-10 11:03 
GeneralGreat sample [modified] Pinmemberzameb1-Sep-10 22:56 
Generalmost cool Pinmemberchristoph braendle20-Aug-10 9:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 20 Aug 2010
Article Copyright 2010 by Jan Vilášek
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid