Click here to Skip to main content
15,891,513 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I want to change my rich textbox color for new input. The textbox loads a text at startup. I want to control that new user input is still highlighted for example red color or yellow background. The new text can be added anywhere and not only at the end. If it would be only at the end I could easily add a red letter there.

The problem behind is that the user should edit a text and the changes should be highlighted.

My code :
C# program
C#
string RTF = @"{\rtf1\ansi\deff0 " +
@"{\colortbl;\red0\green0\blue0;\red255\green0\blue0;} "+
@"line1 \line "+
@"\cf2 "+
@"line 2 \line "+
@"\cf1 "+
@"line 3 "+
@"}";

MemoryStream stream = new MemoryStream(ASCIIEncoding.Default.GetBytes(RTF));
TextRange range = new TextRange(demo.Document.ContentStart, demo.Document.ContentEnd);
range.Load(stream, DataFormats.Rtf);

XAML Code
C#
<RichTextBox HorizontalAlignment="Left" Height="116" Margin="37,266,0,0" Grid.Row="1" x:Name="demo" VerticalAlignment="Top" Width="381">
         
        </RichTextBox>


What I have tried:

I have already added the RichTextBoxFormatBar from Extended WPF Toolkit. It allows the user to format the content but I did not found a solution for setting the default color for new input.
Posted
Updated 26-Jul-16 0:39am
Comments
[no name] 23-Jul-16 11:23am    
Maybe a start, not a nice one more a hack I think. And a lot of things need to be fixed:
private void RichTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
rtb.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
}
Andre Dieme 23-Jul-16 12:35pm    
Thanks a lot! It works great.
I changed the code a bit because this methode could be applied to all Richt textboxes.

private void RichTextBox_TextChanged(object sender, TextChangedEventArgs e)
{
RichTextBox x = (RichTextBox)sender;
x.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
}

1 solution

You can compare both the given text and the new input text.

If any mismatch found, then format it.


string oldText = "whatever";
string newText = rtbGivenText.Text;

for (int i = 0; i < oldText.Length; i++)
{
if (oldText[i]==newText[i])
{
rtbGivenText.Select(i, i+1);
rtbGivenText.SelectionColor = Color.Red;
}
}
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900