WPF RichTextBox 内联更改字体颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17175694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WPF RichTextBox change font color inline
提问by ToastyMallows
I've searched for a while for this solution, so now I'm posting here.
我已经搜索了一段时间来寻找这个解决方案,所以现在我在这里发帖。
Right now I am able to change the foreground color of the whole RichTextBox:
现在我可以改变整体的前景色RichTextBox:
yourRichTextBox.Foreground = Brushes.Red;
I'm also able to change the color of some text that a user has selected with their cursor:
我还可以更改用户使用光标选择的某些文本的颜色:
if(!yourRichTextBox.Selection.IsEmpty){
yourRichTextBox.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
}
But I want to be able to change the color of the next text that the user types.
但我希望能够更改用户键入的下一个文本的颜色。
I have a color picker box that returns the color a user wants the text to be in. So the user is typing in the RichTextBoxin normal black font, then they would click the color picker button, select a color, hit OK and then the next thing they type will be in that color. Is there a way to do this or am I out of luck?
我有一个颜色选择器框,它返回用户希望文本所在的颜色。所以用户输入RichTextBox普通的黑色字体,然后他们会点击颜色选择器按钮,选择一种颜色,点击确定,然后点击下一个他们键入的东西将是那种颜色。有没有办法做到这一点,还是我运气不好?
The only way I can think to do it is to have a buffer that captures each character the user types, and then set the foreground property on each letter typed and then add it back into RichTextBox, ideas?
我能想到的唯一方法是有一个缓冲区来捕获用户键入的每个字符,然后在键入的每个字母上设置前景属性,然后将其添加回RichTextBox,想法?
采纳答案by Oren
The same code that you are using for your Selection works for me. For example:
您用于选择的相同代码对我有用。例如:
<RichTextBox x:Name="yourRichTextBox" TextChanged="yourRichTextBox_TextChanged_1">
<FlowDocument>
<Paragraph>
<Run Text="fdsfdfsda"/>
</Paragraph>
<Paragraph>
<Run/>
</Paragraph>
</FlowDocument>
</RichTextBox>
Code Behind:
背后的代码:
private void yourRichTextBox_TextChanged_1(object sender, TextChangedEventArgs e)
{
yourRichTextBox.Selection.ApplyPropertyValue(RichTextBox.ForegroundProperty, Brushes.Red);
}
Once you start typing, the second letter and onward (the first triggers this change) will be red.
开始输入后,第二个字母及以后的字母(第一个触发此更改)将变为红色。

