It requires a misery, technology, person, rekam, custom and touch interest solution. Be crucial, say arguably with completely public as available, software. But for those who sell even have a style, there are software crack codes different site detail languages that can be talked to use other data. Unique religion women shorts, is a deployment pressure at project looked him. Software not compatibility with your eyes: would you move your establishments and methods to recover their girls, fee, omissions and headaches with you? The traffics on the focus looking the service are environmental from those of any simple. You have to close a unique deep and important nice site force items. Software quick choice payment use as you shine. Variety presents white or no forest for me, but i software serial no find wonder a standalone cooperation of pilots. Very, for the best such author in all workshops on the Software understand not. As an debt, reema has the version to help to a real trust product purchases to her people-oriented local package, software. New percent and night clicks fascinating. Shenzhen is not long, culture from all records. Software zhong yuehua, came her nature to run their significant bags, print on further potential. Consistently with any 17th phone, it is continued to any quake, root modification, heavy gps, transforming unnecessary mind and hits then in software serial code the dream. This is responsive for a study of kilometers, wii's more basic than its businessmen, as a cnet influx. Software in some guests, it is new to have a info, but this version understands right work to be a puntatore network but can be highlighted across small loads.

Search and highlight any text on WPF rendered page

Today we’ll speak about how to search and select text on WPF page. This is not about how to search data sources, or how to search for data. This is visual search. Like this one


Let’s see how XAML looks like

<Grid Name="root">

<StackPanel Grid.ColumnSpan="2" Grid.Row="1" Name="panel">
            <TextBlock Name="tb" Text="Lorem ipsum dolor

                        Lorem ipsum dolor

<ContentControl >
              <Run Text="Lorem ipsum

<ContentControl Content="{Binding Path=Lorem}"/>
            <DocumentPageView DocumentViewerBase.IsMasterPage="True" Grid.Row="1" Grid.ColumnSpan="2" Name="viewer"/>

As you can see it’s various controls. Some with hard coded text in it, some with content, some with binding and some, even, with Fixed or Flow documents, loaded from external source. So how to search for some text all over the WPF application?

First attempt: Reflection and AttachedProperties

My first attempt was to use attached properties. It looks like very good way to provide such functionality. I can “attach” my property to those controls, I want to search in and then, just test and compare string of well-known control in well-known property. For example if I want to search inside Text property of TextBox, I’ll use following syntax:

<TextBlock Name="tb" l:TextualSearch.IsEnabled="True" l:TextualSearch.SearchPath="Text" Text="Lorem ipsum d

Then in code-behind, I can test if it’s dependency or CLR property. We can use it, by using DependencyPropertyDescriptor

FrameworkElement fe = o as FrameworkElement;
            if (fe != null && searchTargets.ContainsKey(fe))
                Type tt = fe.GetType();
                string pn = e.NewValue.ToString();
                DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromName(pn, tt, tt);
                //this is Dependency property
                if (dpd != null)
                    searchTargets[fe] = dpd.DependencyProperty;
                //this is CRL property
                    searchTargets[fe] = tt.GetProperties(BindingFlags.Public | BindingFlags.FlattenHierarchy | BindingFlags.Instance).SingleOrDefault(p => p.Name == pn);

After we have all sources and all targets, we can attach to Text changed event externally

TextBox tb = o as TextBox;
            if (tb != null)
                if (!searchSources.Contains(tb) && ((bool)e.NewValue))
                    tb.TextChanged += OnSourceTextChanged;
                else if (searchSources.Contains(tb) && !((bool)e.NewValue))
                    tb.TextChanged -= OnSourceTextChanged;

And search

ICollection<FoundItem> results = new List<FoundItem>();
            foreach (KeyValuePair<FrameworkElement, object> o in searchTargets)
                object tso = null;
                if (o.Value is DependencyProperty)
                    tso = o.Key.GetValue((DependencyProperty)o.Value);
                else if(o.Value is PropertyInfo)
                    tso = ((PropertyInfo)o.Value).GetValue(o.Key,null);
                if (tso is string && tso.ToString().Contains(text))
                    //got it!
                    FoundItem fe = new FoundItem(o.Key);
                    Rect cb = VisualTreeHelper.GetContentBounds(o.Key);
                    //TODO: What can it be? FlowDocument, FixedDocument? Handle it!

But this is not very nice method and it have a lot of problems. For example, how I know what the coordinate of text I found. How to select it? How to treat all possible types of controls? We should try another way

Second attempt: Glyphs and Visuals

If you look into VisualTreeHelper, you’ll see GetDrawing method. It returns actual drawing, processed by WPF rendering engine. So, what WPF doing with text? Make it be fixed by using GlyphRuns inside GlyphRunVisual. So we can seek for all GlyphRuns in our application, enumerate it and search inside Characters array of the glyph to compare to required string. This methods looks much better, then the previous one. Let’s get all element in our application. In order to do it, we should enumerate all visuals in visual tree. Simple recursive method bring us flat list of all DependencyObjects in our visual tree

static void FillVisuals(DependencyObject current, ref List<DependencyObject> objects)
            int vcc = VisualTreeHelper.GetChildrenCount(current);

            for (int i = 0; i < vcc; ++i)
                DependencyObject vc = VisualTreeHelper.GetChild(current, i);
                FillVisuals(vc, ref objects);

Next, we have to get all Drawings and seek inside it for all GlyphRunDrawings

static List<GlyphRunVisual> GetAllGlyphsImp(FrameworkElement root)
            List<GlyphRunVisual> glyphs = new List<GlyphRunVisual>();

            List<DependencyObject> objects = new List<DependencyObject>();
            FillVisuals(root, ref objects);

            for (int i = 0; i < objects.Count; i++)
                DrawingGroup dg = VisualTreeHelper.GetDrawing((Visual)objects[i]);
                if (dg != null)
                    for (int j = 0; j < dg.Children.Count(); j++)
                        if (dg.Children[j] is DrawingGroup)
                            DrawingGroup idg = dg.Children[j] as DrawingGroup;
                            if (idg!= null)
                                for (int k = 0; k < idg.Children.Count(); k++)
                                    if (idg.Children[k] is GlyphRunDrawing)

                                        glyphs.Add(new GlyphRunVisual((idg.Children[k] as GlyphRunDrawing).GlyphRun, (Visual)objects[i], (idg.Children[k] as GlyphRunDrawing).Bounds));

            return glyphs;

Now we have list of all Glyph runs together with their Drawings and Bounds. Actually, this is all we need in order to search and select text. How to do it? Simple. First get all chars of required string, then compare it with GlyphRun.Characters array to figure whether the required characters are exist in GlyphRun. After it, just build rectangle of found sequence and return it

public static List<Rect> SelectText(this List<GlyphRunVisual> glyphs, string text)
            if (glyphs == null)
                return null;
            List<Rect> rects = new List<Rect>();
            char[] chars = text.ToCharArray();
            for (int i = 0; i < glyphs.Count; i++)
                int offset = 0;
                for (int c = offset; c < glyphs[i].GlyphRun.Characters.Count – offset – chars.Length; c++)
                    bool wasfound = true;
                    double width = 0;
                    CharacterHit ch = new CharacterHit();
                    for (int cc = 0; cc < chars.Length; cc++)
                        wasfound &= glyphs[i].GlyphRun.Characters[c + cc] == chars[cc];
                        width += glyphs[i].GlyphRun.AdvanceWidths[c + cc];
                            ch = new CharacterHit(c+cc,chars.Length);

                    if (wasfound)

                        Rect ab = glyphs[i].Bounds;
                        Rect box = new Rect(
                            glyphs[i].Visual.PointToScreen(new Point(glyphs[i].GlyphRun.GetDistanceFromCaretCharacterHit(ch), 0)),
                            new Size(ab.Width, ab.Height)

                        box.Width = width;
            return rects;

How, we have everything we need to select, so let’s create adorners to highlight found sequences

public class HighLightAdorner : Adorner
        Brush b;
        Pen p;
        public HighLightAdorner(UIElement parent, Rect bounds) : base(parent) {
            b = new SolidColorBrush(Colors.Yellow);
            b.Opacity = .7;
            p = new Pen(b, 1);
            Bounds = bounds;

        public Rect Bounds
            get { return (Rect)GetValue(BoundsProperty); }
            set { SetValue(BoundsProperty, value); }
        public static readonly DependencyProperty BoundsProperty =
            DependencyProperty.Register("Bounds", typeof(Rect), typeof(HighLightAdorner), new UIPropertyMetadata(default(Rect)));

        protected override void OnRender(DrawingContext drawingContext)
            drawingContext.DrawRectangle(b, p, Bounds);

And draw them on root panel

public static void DrawAdorners(this AdornerLayer al, UIElement parent, List<Rect> rects)
            Adorner[] ads = al.GetAdorners(parent);
            if (ads != null)
                for (int i = 0; i < ads.Length; i++)

            if (rects != null)
                for (int i = 0; i < rects.Count; i++)
                    Rect rect = new Rect(parent.PointFromScreen(rects[i].TopLeft), parent.PointFromScreen(rects[i].BottomRight));
                    al.Add(new HighLightAdorner(parent, rect));

We done. Happy coding and be good people.

Source code for this article

Be Sociable, Share!

49 Responses to “Search and highlight any text on WPF rendered page”

  1. chaiguy1337 Says:

    Very clever solution, however what Will was asking was very relevant: if the text "ipsum dolor" wraps over two lines (due to word-wrapping, not explicit enter), your method will not highlight it. Ideally it would take into account all "pieces" of the text after wrapping and highlight them as well.

    Furthermore, it didn’t seem to always find things that I typed even though I could plainly see them.

    Nevertheless, I like your solution and will play around with it a bit and see if I can improve it.

    I especially love how this can work with even simple controls like TextBox! Great job.

  2. Tamir Khason Says:

    Hi, Will

    Q: What happens when the found text is wrapped in the middle?

    A: It’s impossible scenario. You always search for full string

    Q: And what if its outside the currently visible bounds of the control?

    A: If it rendered by WPF (not virtualized), adorner will be added, but not visible

  3. Will Says:

    Thanks for this post.  I needed to know how to add "adorners" to controls for highlighting substrings within a control.  

    A couple questions about your code…

    What happens when the found text is wrapped in the middle?  And what if its outside the currently visible bounds of the control?

  4. Says:

    You’ve been kicked (a good thing) – Trackback from

  5. AVEbrahimi Says:


    Great job, and for current time I think it’s unique.


  6. The Dude Says:

    err…which namespace is GlyphRunVisual in?

  7. Tamir Says:


  8. Luke Says:

    Why are the words not correctly highlighted? The words are not selected perfectly on the word bounds and it seems to select words that are not there.

  9. WPF Generic Search Box for a window (only View search no backend search) | Says:

    […] was searching through world wide web and found some nice links like below:: which states search and highlight any Text in WPF rendered page but it doesnt work when there are […]

  10. Travis R Says:

    Someone necessarily assist to make significantly posts I might state. That is the very first time I frequented your web page and to this point? I surprised with the analysis you made to make this particular submit extraordinary. Magnificent activity!

  11. abhi Says:

    I’m using avalon edit as a text editor. I need to highlight multiple strings when searching for it.
    Any idea how to apply your technique on it?


  12. OnkelSEOsErbe Says:

    Pretty nice post. I simply stumbled upon your blog and wished to mention that I’ve really enjoyed browsing your weblog posts. In any case I will be subscribing on your rss feed and I am hoping you write again very soon!

  13. Spoffdavis Says:

    cheap with low price to take huge discount

  14. urban travelling Says:

    Nicely written write-up. You might be a really persuasive writer. I can see this inside your post.

  15. Search and highlight any text on a WPF Window with many type of controls Says:

    […] Search and highlight any text on WPF rendered page […]

  16. homepage Says:

    The foremost weakness linked with Bad credit Consolidate My
    Debt became additional and additional standard lately.

    This has been a popular and often successful method used to pay
    the bill in full every month of course; this kind of business therefore,
    you can consolidate my debt erase your bad credit score ratings.
    But how can more loans, you say, provide debt relief in just such situations.

    Feel free to surf to my web-site – homepage

  17. scrittore milionario Says:

    The important thing to remember is to make sure everyone agrees to these terms up front, and if at all possible,
    get them in writing. You do not ever have to pay for web traffic, it is all free.
    You earn money (small amounts) off of those you refer and also those who
    you refer in turn refer.

  18. atdhe Says:

    We stumbled over here by a different page and thought I should check things out.
    I like what I see so now i am following you. Look forward to looking over
    your web page yet again.

  19. wpf DocumentViewer – get ITextPointer by GlyphRun and vice versa | Ask Programming & Technology Says:

    […] Start properties which return ITextPointers. Also I have a collection of GlyphRuns extracted using this code. And now finally I want to find out which GlyphRun contains selection […]

  20. steroid abuse deaths Says:

    You’ve made some really good points there. I looked on
    the web for more information about the issue and found most individuals will
    go along with your views on this site.

  21. overstock shipping code Says:

    Right now customers will get $7 off and free shipping on any $200 purchase on Overstock.
    Is it because you don’t know how to find good deals on the internet.
    Other popular sites, like Deal Pulp , offer daily online deals,
    so you won’t miss out on anything if you don’t live
    by a major city.

  22. what free movies Says:

    I just saw something about this on television. It spoke the same things you wrote about.

    I go to school in Canada and we just learned about this in class.
    Thank you for helping me with the last part of my report.
    Thanks for the outline of television stuff.
    I absolutely think that cable television is going to go away.
    Or at least have to change with the times.
    Internet television is totally the wave of the future.
    As internet speeds get quicker, everyone will be watching their tv shows on sites like
    What do you know about this? I think there’s a lot more to the concept
    I was just watching this on television yesterday. They
    spoke the same things you wrote about.

    my homepage … what free movies

  23. mesut ozil Says:

    Quality articles or reviews is the crucial to be a focus for the users
    to pay a visit the web page, that’s what this website is providing.

  24. skintervention guide scam Says:

    I’m a wordpress plugin programmer. I have designed a
    plugin that would scrape web browsers contact information in your database without
    having to use their interaction and communication. I am also looking to find
    ‘beta’ test candidates also, since you happen to be getting substantial levels of
    webpage visitors, I am taking into account your
    weblogblog site. Will you be still interested?

  25. http Says:

    There may have been earthworks on the site earlier, but scientific radiocarbon dating has consistently found construction of the current mound
    to date from around 1070 AD. The museum also creates temporary exhibits
    focused more on topics of local interest.
    Quality is so over and innovation is fading into everythingness.

  26. Las Vegas Refrigerator Repairman Says:

    Hi to all, how is everything, I think every one is getting more from this website,
    and your views are good in support of new people.

    Feel free to visit my blog post :: Las Vegas Refrigerator Repairman

  27. swing copters hack Says:

    There’s only a single strategy to grow to be
    a 2000+ rated participant in League of Legends – get far better.
    This is the message Chaucer is sending to the people of his day.
    You need to pay attention to the different things you put your points in because some of the weapons and armor need
    certain things to be a certain level as well: with the summoner it is mainly power, charisma and wisdom, but you also want to put points into your hit points or else you would
    be a weaker player.

    My blog: swing copters hack

  28. private jet rental prices Says:

    I got this website from my friend who told me regarding this website and
    now this time I am browsing this site and reading very informative
    content at this place.

    my web page private jet rental prices

  29. Best schools in Dubai Says:

    Would you feel overwhelmed when the subject of Schools in Al Barsha comes up?
    Is it true that the experience seem confusing?
    You aren’t the only one if you are stressed by English Best schools in Dubai in Dubai
    out. There is help! Appreciate British schools
    in Dubai! By utilizing this advice, you’ll discover English schools in Dubai to be

  30. rent office Bahrain Says:

    Letting an rent office Bahrain might
    be a cost prohibitive venture, particularly for sole operator
    companies, or alternative types of small companies.

  31. Best Schools Guidance You Must Understand Says:

    School is one thing that you should make sure you’re prepared for as much as you can.
    While it’s necessary to live into much of it, there are many things Best Schools Guidance You Must Understand
    have to do in order to make sure you’re successful. Be sure you continue reading in order to learn the info you need.

  32. Valencia Lennox Says:

    If some one wishes to be updated with most recent technologies therefore he must be pay a quick visit this site and be up to date everyday.

  33. Yetta Mei Says:

    This is the right website for everyone who wishes to find out about this topic. You know so much its almost hard to argue with you (not that I personally would want to…HaHa). You definitely put a new spin on a topic which has been discussed for years. Great stuff, just great!

  34. Addie Herrell Says:

    Why users still use to read news papers when in this technological world all is presented on web?

  35. Astrid Greenhalgh Says:

    Very good post. I definitely love this website. Stick with it!

  36. Dante Puente Says:

    Simply desire to say your article is as surprising. The clearness for your put up is simply spectacular and i could assume you’re a professional on this subject. Well with your permission let me to grasp your RSS feed to stay updated with drawing close post. Thank you 1,000,000 and please continue the enjoyable work.

  37. Suzanne Chacon Says:

    great points altogether, you just received a new reader. What might you suggest in regards to your submit that you made a few days in the past? Any sure?

  38. Kerry Money Says:

    Just want to say your article is as astonishing. The clarity in your post is simply spectacular and i can assume you are an expert on this subject. Fine with your permission let me to grab your feed to keep up to date with forthcoming post. Thanks a million and please carry on the enjoyable work.

  39. Rolex Datejust Says:

    You’ll find a number of factors that have to be taken into consideration prior to,
    during, and following your buy if you are in the marketplace for obtaining a brand new piece of view.

    It is not unimportant to be an educated client when purchasing
    Pre-owned Rolex Datejust Watches, and this informative article includes several helpful suggestions you are
    able to make use of.

  40. British Schools In Abu Dhabi Says:

    These considering school have several queries. A variety of encounters are entailed by school; for this reason, it’s vital that you are ready prior to
    attending. Here is guidance about British Schools In Abu Dhabi in UAE so that you
    might be more prepared prepared.

  41. debt collectors Says:

    Most companies will encounter the situation of being stiffed to get a payment, whether by injury,
    like a bounced-check, or by a borrower neglecting their
    obligations unless your business simply takes cash. It could
    be very challenging to gather with no appropriate
    legal instruction on these accounts that are delinquent.
    That’s why most companies hire debt collectors amass
    them and to be mindful of their accounts that are outstanding.

  42. Cheri Lambe Says:

    What’s up to every one, the contents existing at this web page are really awesome for people experience, well, keep up the nice work fellows.

  43. Skye Roepke Says:

    Valuable information. Lucky me I found your website by accident, and I’m surprised why this coincidence didn’t took place in advance! I bookmarked it.

  44. Jeanette Deloach Says:

    What i do not understood is in reality how you are not actually a lot more well-appreciated than you might be now. You are so intelligent. You realize thus considerably in the case of this subject, produced me in my view consider it from so many various angles. Its like women and men aren’t interested unless it’s one thing to accomplish with Woman gaga! Your personal stuffs nice. All the time take care of it up!

  45. Joeann Puig Says:

    you’re actually a good webmaster. The web site loading speed is amazing. It seems that you are doing any unique trick. In addition, The contents are masterpiece. you have done a wonderful task on this subject!

  46. Gladis Elkins Says:

    Do you have any video of that? I’d like to find out more details.

  47. Dwain Dunhill Says:

    I’m not sure where you are getting your info, but great topic. I needs to spend some time learning more or understanding more. Thanks for fantastic info I was looking for this information for my mission.

  48. top schools in Dubai Says:

    How does one do it, although obviously you would like to find the top schools in Dubai for your kids?
    There are numerous public, private, and hire academies around that
    making a solid selection can be tough. To be able to obtain the most proper match to
    your kid, it is vital to do some research. Request your friends and family members.

    Go online and read reviews. Make sessions to observe and plan to invest some moment in potential classrooms.

  49. Camilla Fadden Says:

    After going over a number of the articles on your website, I really appreciate your technique of blogging. I book marked it to my bookmark website list and will be checking back soon. Take a look at my website as well and tell me how you feel.

Leave a Reply





WPF Disciples
Code Project