C#|XAML : ListBox – Search, Filter, and Highlight (3/3)

Highlight colors. by pasukaru76, on Flickr
Highlight colors., a photo by pasukaru76 on Flickr.

In part 1  and part 2 we set up our ListBox and search TextBox in MainPage.XAML and filtered the list on-the-fly for the text entered in the text box. To see search/filter/highlight code in action in a published app, you can download my app for free.

After having filtered the list, in this post we will add code to highlight the searched text in each field of the items. The highlighted text will be in current accent color on the device, italicized, and underlined.

Let’s open MainPage.xaml.cs and add two new fields at MainPage class level:

        EventHandler _listBoxItemsRearrangedHandler;
        bool    _trapListBoxLayoutUpdate = true;

…and in the constructor initialize the handler:

            _listBoxItemsRearrangedHandler = new EventHandler(listBoxItems_Rearranged);

In the private method prepareFilteredList, we created in Part 2, set the _trapListBoxLayoutUpdate flag and also start listening to LayoutUpdated event of listBoxTextItems:

            _trapListBoxLayoutUpdate = true;
            listBoxTextItems.LayoutUpdated -= new EventHandler(_listBoxItemsRearrangedHandler);
            listBoxTextItems.LayoutUpdated += new EventHandler(_listBoxItemsRearrangedHandler);

Add following two methods for the core highlighting logic:

        void listBoxItems_Rearranged(object sender, EventArgs e)
            if (_trapListBoxLayoutUpdate)
                foreach (var ob in listBoxTextItems.Items)
                    ListBoxItem lbi = listBoxTextItems.ItemContainerGenerator.ContainerFromItem(ob) as ListBoxItem;
                    if (lbi != null)
                        IEnumerable<TextBlock> _allTextBlocks = ViewHelpers.GetChildrenByType<TextBlock>(VisualTreeHelper.GetChild(lbi, 0));
                        foreach (TextBlock _txtBlock in _allTextBlocks)
                            if (
                                _txtBlock.Name == "templateTextBlockName" ||
                                _txtBlock.Name == "templateTextBlockNote" ||
                                _txtBlock.Name == "templateTextBlockAdd"
                                ) &&
                                HightlightText(_txtBlock, textBoxSearch.Text);
                _trapListBoxLayoutUpdate = false;
        public static void HightlightText(TextBlock textBlockTarget, string highlightedText)

            string Text = textBlockTarget.Text;
            int _indexOfHighlightedTextInTarget = Text.ToUpper().IndexOf(highlightedText.ToUpper());
            Color highlightColor = (Color)Application.Current.Resources["PhoneAccentColor"];
            Run r = new Run();
            r.Text = Text.Substring(0, _indexOfHighlightedTextInTarget);

            r = new Run();
            r.Text = highlightedText;
            r.FontWeight = FontWeights.Bold;
            r.FontStyle = FontStyles.Italic;
            r.TextDecorations = TextDecorations.Underline;
            r.Foreground = new SolidColorBrush(highlightColor);

            r = new Run();
            r.Text = Text.Substring(_indexOfHighlightedTextInTarget + highlightedText.Length, Text.Length - (_indexOfHighlightedTextInTarget + highlightedText.Length));

F5 and when the form is up, type Bill in the text box. You will notice as you are typing list is filtering and the text being typed in the text box is getting highlighted in different fields of the items in the ListBox.


A more extensive implementation can be found in this app.

Hope you find this code useful.

Happy searching/filtering/highlighting πŸ˜€

6 thoughts on “C#|XAML : ListBox – Search, Filter, and Highlight (3/3)

  1. Pingback: Dew Drop – March 5, 2014 (#1735) | Morning Dew

  2. Pingback: C#|XAML : ListBox – Search, Filter, and Highlight (2/3) | Sharp Statements

  3. Pingback: C#|XAML : ListBox – Search, Filter, and Highlight (3/3)

  4. Hi sir i Got The Following Error How To Solve This

    Error 1 The name ‘ViewHelpers’ does not exist in the current context e:\new folder\visual studio 2013\Projects\PhoneApp8\PhoneApp8\MainPage.xaml.cs 100 65 PhoneApp8

    • Add below given methods & replace that line with this.

      IEnumerable _allTextBlocks = GetDescendantsOfType(VisualTreeHelper.GetChild(lbi, 0));

      public IEnumerable GetDescendantsOfType(DependencyObject start) where T : DependencyObject
      return GetDescendants(start).OfType();

      public IEnumerable GetDescendants(DependencyObject start)
      var queue = new Queue();
      var count = VisualTreeHelper.GetChildrenCount(start);

      for (int i = 0; i 0)
      var parent = queue.Dequeue();
      var count2 = VisualTreeHelper.GetChildrenCount(parent);

      for (int i = 0; i < count2; i++)
      var child = VisualTreeHelper.GetChild(parent, i);
      yield return child;

      From: WinRT XAML Toolkit

  5. Pingback: Dynamically highlighting textbox parts when filtering | Around computing

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s