Wednesday, January 30, 2013

line selection in WPF richtextbox


Methods to highlight /or change the colors of line inside a WPF RichTextBox element.

Select a line according to its index number:
TextPointer start = richTextBox1.CaretPosition.GetLineStartPosition(LineNumber);
TextPointer stop = richTextBox1.CaretPosition.GetLineStartPosition(LineNumber+ 1);
TextRange textrange = new TextRange(start, stop);
textrange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Blue));


Select all line:
TextPointer start = richTextBox1.CaretPosition.DocumentStart;
TextPointer stop = richTextBox1.CaretPosition.DocumentEnd;
TextRange textrange = new TextRange(start, stop);
textrange.ApplyPropertyValue(TextElement.ForegroundProperty, new SolidColorBrush(Colors.Black));

if you get an error of type "The calling thread cannot access this object because a different thread owns it" or if the program "freezes" in an inexplicable way. You should you the Dispatcher to avoid thread conflict:

private delegate void SetColorDelegate();


private void ExecuteInstruction()
        {
            try
            {
                Dispatcher.BeginInvoke(new SetColorDelegate(setcolor));
          }
            catch (Exception e)
            {
                //The calling thread cannot access this object because a different thread owns it
            }
}


private void setcolor()
        {
            TextPointer start = richTextBox1.CaretPosition.GetLineStartPosition(ProtocolPointer);
            TextPointer stop = richTextBox1.CaretPosition.GetLineStartPosition(ProtocolPointer + 1);
            TextRange textrange = new TextRange(start, stop);
             textrange.ApplyPropertyValue(TextElement.ForegroundProperty, new               SolidColorBrush(Colors.Blue));
        }