WPF TextBlock highlight certain parts based on search condition

后端 未结 9 1162
遇见更好的自我
遇见更好的自我 2020-12-01 08:42

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.

9条回答
  •  孤街浪徒
    2020-12-01 09:00

    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);
    
                        runs.Insert(i - 1 < 0 ? 0 : 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 += 3;
                    }
                }
            }
        }
    }
    

提交回复
热议问题