0

I'm trying to make my WPF RichTextBox appear like a coding page.

I marked some words to determind it's a keyword or a string,... Now I have text like this:

<@$keyword>int<keyword$@> sum;

sum = 1;

Console.WriteLine(<@$string>"{0}"<string$@>,sum);

The result should be like this:

int sum;
sum = 1;
Console.WriteLine("{0}",sum);

But "int" is blue and "{0}" is pink.

Here is my xaml RichTextBox code:

<RichTextBox x:Name="richTextBox"
                     VerticalScrollBarVisibility="Auto">
            <FlowDocument>
                <Paragraph>
                    <Run Text="{Binding codeContent}"/>
                </Paragraph>
            </FlowDocument>
        </RichTextBox>

My question refer to this stackoverflow question but it not seem to solve my problem.

Because my WPF RichTextBox built up with FlowDocument inside, we can't get the content text by things like String st = myRichtextBox.Text, we need to use TextRange to get the text inside it: TextRange tr = new TextRange(rtb.Document.ContentStart,rtb.Document.ContentEnd) .

But another problem is it get the whole text, not get a part of content text that I want. Example: RichTextBox rtb contain:<@$keyword>int<keyword$@> sum;sum = 1;Console.WriteLine(<@$string>"{0}"<string$@>,sum); and I want to get just <@$keyword>int<keyword$@>and <@$string>"{0}"<string$@> and edit it not the whole text.

Community
  • 1
  • 1
  • Possible duplicate of [How to select text from the RichTextBox and then color it?](http://stackoverflow.com/questions/3707120/how-to-select-text-from-the-richtextbox-and-then-color-it) – bichito Mar 18 '17 at 14:08
  • Yes, it's the same question but different technic, I'm using **WPF RichTextBox** which not allow you to get the contain text that easy. I found it we can use TextRange to get all the text and edit it. But how can I get the exactly text to edit it? – Nguyễn Khương Mar 18 '17 at 14:19
  • http://stackoverflow.com/questions/957441/richtextbox-wpf-does-not-have-string-property-text This will do the trick – bichito Mar 18 '17 at 14:29
  • @efekctive that's how to get the whole text inside it. But I just want to get a small part of the text. Example: `<@$keyword>int` but not `<@$keyword>int sum;sum = 1; Console.WriteLine(<@$string>"{0}",sum);` – Nguyễn Khương Mar 18 '17 at 14:41
  • https://msdn.microsoft.com/en-us/library/aa970909(v=vs.110).aspx – bichito Mar 18 '17 at 14:48
  • Thank you, I'm working on it and will put down the answer if I found it – Nguyễn Khương Mar 18 '17 at 14:54

1 Answers1

1
TextRange tr = new TextRange(rtb.Document.ContentStart,rtb.Document.ContentEnd) 

tr.Text gives you the plain string of the contents. Now you have an string to use with regex/substrings following:

How to select text from the RichTextBox and then color it?

Community
  • 1
  • 1
bichito
  • 1,406
  • 2
  • 19
  • 23