views:

1517

answers:

2

Hello,

I have TextBlock that has Inlines dynamicly added to it (basically bunch of Run objects that are either italic or bold).

In my application I have search function.

I want to be able to highlight TextBlock's text that is in being searched for.

By highlighting I mean changing certain parts of TextBlock text's color (keeping in mind that it may highlight several different Run objects at a time).

I have tried this example http://blogs.microsoft.co.il/blogs/tamir/archive/2008/05/12/search-and-highlight-any-text-on-wpf-rendered-page.aspx

But it seams very unstable :(

Is there easy way to solve this problem?

+1  A: 

Ended up writing following code

At moment has few bugs, but solves the problem

            if (Main.IsFullTextSearch)
        {
            for (int i = 0; i < runs.Count; i++)
            {
                if (runs[i] is Run)
                {
                    Run originalRun = (Run)runs[i];

                    if (Main.SearchCondition != null && originalRun.Text.ToLower().Contains(Main.SearchCondition.ToLower()))
                    {
                        int pos = originalRun.Text.ToLower().IndexOf(Main.SearchCondition.ToLower());

                        if (pos > 0)
                        {
                            Run preRun = CloneRun(originalRun);
                            Run postRun = CloneRun(originalRun);

                            preRun.Text = originalRun.Text.Substring(0, pos);
                            postRun.Text = originalRun.Text.Substring(pos + Main.SearchCondition.Length);

                            if (i - 1 < 0)
                                runs.Insert(0, preRun);
                            else
                                runs.Insert(i - 1, preRun);

                            runs.Insert(i + 1, new Run(" "));
                            runs.Insert(i + 2, postRun);

                            originalRun.Text = originalRun.Text.Substring(pos, Main.SearchCondition.Length);

                            SolidColorBrush brush = new SolidColorBrush(Colors.Yellow);
                            originalRun.Background = brush;

                            i = i + 3;
                        }
                    }
                }
            }
        }
Daniil Harik
A: 

Can you please provide the full code. Because i am not getting any CloneRun method. Thanks in advance.