title: Highlighting keywords in a richtextbox in WPF
body: <p>I'm making a program which needs to look through a paragraph of text and find how many times a certain keyword/keywords appear. It also has to highlight each of these key words in the text. </p>
  
  <p>I have managed to make he interface and it can now track how many times the word appears but I am really stuck for how to highlight where the keywords appear. I will post my code below, any help is greatly appreciated on how to search for and highlight text inside a richtextbox. Since this is in WPF the obvious richtextbox.find() is not avaliable for use. </p>
  
  <pre><code>class TextAnalyser
  {
      public int FindNumberOfOccurances(List&lt;string&gt; keywords, string email)
      {
          int occurances = 0;
          foreach (string keyword in keywords)
          {
              occurances += email.ToUpper().Split(new string[] { keyword.ToUpper() }, StringSplitOptions.None).Count() - 1; 
          }
          return occurances;
      }
  
      public void TurnTextRed(List&lt;string&gt; keywords, string email, RichTextBox TextBox)
      {
          foreach(string keyword in keywords)
          {
          }
      }
  
      public List&lt;string&gt; ConvertTextToList(string text)
      {
          char[] splitChars = {};
          string[] ArrayText = text.Split( splitChars, StringSplitOptions.RemoveEmptyEntries);
          return ArrayText.ToList&lt;string&gt;();
      }
  
      public string GetStringFromTextBox(RichTextBox TextBox)
      {
          var textRange = new TextRange(
              TextBox.Document.ContentStart,
              TextBox.Document.ContentEnd
          );
          return textRange.Text;
      }
  }
  </code></pre>
  
  <p>And here is my Main Window</p>
  
  <pre><code>public partial class MainWindow : Window
  {
      public MainWindow()
      {
          InitializeComponent();
      }
  
      private void AnalyseButton_Click(object sender, RoutedEventArgs e)
      {
          var textTool = new TextAnalyser();
          var keyWords = textTool.ConvertTextToList(textTool.GetStringFromTextBox(WordTextBox).Trim());
          var email = textTool.GetStringFromTextBox(EmailTextBox).Trim();
          int usesOfWord = textTool.FindNumberOfOccurances(keyWords, email);
          Occurances.Text = usesOfWord.ToString();
      }
  }
  </code></pre>