Thursday, August 1, 2013

Setting background color in WPF RichTextBox


Recently I encountered a situation where I was to highlight a word in WPF RichTextBox. So I thought, I should share a small tip to show how to highlight a word (by setting background color) in a WPF Rich TextBox. Here is the code:

        /// <summary>
        /// This method highlights a word with a given color in a WPF RichTextBox
        /// </summary>
        /// <param name="richTextBox">RichTextBox Control</param>
        /// <param name="word">The word which you need to highlighted</param>
        /// <param name="color">The color with which you highlight</param>
        private void HighlightWordInRichTextBox(RichTextBox richTextBox, String word, SolidColorBrush color)
        {
            //Current word at the pointer
            TextRange tr = new TextRange(richTextBox.Document.ContentEnd, richTextBox1.Document.ContentEnd);
            tr.Text = word;
            tr.ApplyPropertyValue(TextElement.BackgroundProperty, color);
        }


1 comment: