简体   繁体   English

如何从WPF RichTextBox中选择文本,然后替换文本并为其着色

[英]How to select text from WPF RichTextBox then replace and color it

I'm trying to make my WPF RichTextBox appear like a coding page. 我试图使我的WPF RichTextBox看起来像一个编码页。

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. 但是“ int”是蓝色,“ {0}”是粉红色。

Here is my xaml RichTextBox code: 这是我的xaml RichTextBox代码:

<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. 我的问题是指此stackoverflow问题,但似乎无法解决我的问题。

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) . 由于我的WPF RichTextBox内置了FlowDocument,因此无法通过String st = myRichtextBox.Text类的内容获取内容文本,我们需要使用TextRange来获取其中的文本: 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); 示例:RichTextBox rtb包含: <@$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. 我只想获取<@$keyword>int<keyword$@><@$string>"{0}"<string$@>而不是编辑整个文本。

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

tr.Text gives you the plain string of the contents. tr.Text为您提供内容的纯字符串。 Now you have an string to use with regex/substrings following: 现在,您可以使用以下字符串与正则表达式/子字符串一起使用:

How to select text from the RichTextBox and then color it? 如何从RichTextBox中选择文本,然后为其着色?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM