Click here to Skip to main content
15,860,859 members
Articles / Desktop Programming / WPF

Highlight Searched Text in WPF ListView

Rate me:
Please Sign up or sign in to vote.
4.91/5 (19 votes)
20 Aug 2010CPOL2 min read 84.5K   4K   38   19
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.

XML
<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.

C#
 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.

C#
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.

C#
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.

C#
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.

C#
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.

C#
Run runx = new Run(item);

runx.Background = Brushes.Red;

tb.Inlines.Add(item);

The code to change text in the background in full:

C#
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)


Written By
Software Developer student
Czech Republic Czech Republic
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionOptimizations Pin
FocusedWolf22-Jun-12 6:55
FocusedWolf22-Jun-12 6:55 
AnswerA full rewrite ;P Pin
FocusedWolf22-Jun-12 11:03
FocusedWolf22-Jun-12 11:03 
Questionworks well for small documents, but how can i speed it up? Pin
I_Need_Help20-Dec-11 6:31
I_Need_Help20-Dec-11 6:31 
GeneralListview Contents truncated and reordered Pin
muthuprakash25-Apr-11 0:53
muthuprakash25-Apr-11 0:53 
GeneralRe: Listview Contents truncated and reordered Pin
Jan Vilášek7-May-11 4:23
Jan Vilášek7-May-11 4:23 
GeneralThank You Pin
muthuprakash21-Apr-11 23:25
muthuprakash21-Apr-11 23:25 
GeneralRe: Thank You [modified] Pin
Jan Vilášek22-Apr-11 5:54
Jan Vilášek22-Apr-11 5:54 
GeneralRe: Thank You Pin
muthuprakash22-Apr-11 21:01
muthuprakash22-Apr-11 21:01 
GeneralListView Not highlighted fully Pin
muthuprakash21-Apr-11 23:24
muthuprakash21-Apr-11 23:24 
GeneralRe: ListView Not highlighted fully Pin
Member 834570123-Mar-12 8:47
Member 834570123-Mar-12 8:47 
GeneralVery good code! Pin
robyg721126-Nov-10 10:43
robyg721126-Nov-10 10:43 
GeneralRe: Very good code! Pin
Jan Vilášek27-Nov-10 0:26
Jan Vilášek27-Nov-10 0:26 
GeneralRe: Very good code! Pin
robyg721128-Nov-10 20:43
robyg721128-Nov-10 20:43 
GeneralRe: Very good code! Pin
Jan Vilášek29-Nov-10 4:38
Jan Vilášek29-Nov-10 4:38 
GeneralCool!! Pin
DanielGutierrez21-Sep-10 11:06
DanielGutierrez21-Sep-10 11:06 
GeneralMy vote of 5 Pin
DanielGutierrez21-Sep-10 11:03
DanielGutierrez21-Sep-10 11:03 
GeneralGreat sample [modified] Pin
zameb1-Sep-10 22:56
zameb1-Sep-10 22:56 
Generalmost cool Pin
christoph brändle20-Aug-10 9:24
christoph brändle20-Aug-10 9:24 

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

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