[英]WPF RichTextBox change font color inline
我已经搜索了一段时间来寻找这个解决方案,所以现在我在这里发帖。
现在我可以改变整个RichTextBox
的前景色:
yourRichTextBox.Foreground = Brushes.Red;
我还可以更改用户使用光标选择的某些文本的颜色:
if(!yourRichTextBox.Selection.IsEmpty){
yourRichTextBox.Selection.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);
}
但我希望能够更改用户键入的下一个文本的颜色。
我有一个颜色选择器框,它返回用户希望文本所在的颜色。所以用户在RichTextBox
中输入普通黑色字体,然后他们会点击颜色选择器按钮,选择一种颜色,点击确定,然后他们输入的下一件事将是那种颜色。 有没有办法做到这一点,还是我运气不好?
我能想到的唯一方法是有一个缓冲区来捕获用户键入的每个字符,然后在键入的每个字母上设置前景属性,然后将其添加回RichTextBox
,想法?
您用于选择的代码与我相同。 例如:
<RichTextBox x:Name="yourRichTextBox" TextChanged="yourRichTextBox_TextChanged_1">
<FlowDocument>
<Paragraph>
<Run Text="fdsfdfsda"/>
</Paragraph>
<Paragraph>
<Run/>
</Paragraph>
</FlowDocument>
</RichTextBox>
背后的代码:
private void yourRichTextBox_TextChanged_1(object sender, TextChangedEventArgs e)
{
yourRichTextBox.Selection.ApplyPropertyValue(RichTextBox.ForegroundProperty, Brushes.Red);
}
开始输入后,第二个字母及以上(第一个字母触发此更改)将为红色。
我有另一个可能很有趣的解决方案。 关键是使用 RichTextBox 的 Document 属性。
private void Print(string s)
{
if (s != null)
{
var paragraph = new Paragraph();
paragraph.Inlines.Add(new Bold(new Run($"{DateTime.Now:HH:mm:ss.fff}: ")) { Foreground = Brushes.Green });
paragraph.Inlines.Add(new Run($"{(s.EndsWith(Environment.NewLine) ? s : s + Environment.NewLine)}"));
LogView.Document.Blocks.Add(paragraph);
LogViewScrollViewer.ScrollToEnd();
}
}
Xml:
<ScrollViewer x:Name="LogViewScrollViewer">
<RichTextBox x:Name="LogView" AcceptsReturn="True" IsReadOnly="True">
<RichTextBox.Resources>
<Style TargetType="Paragraph">
<Setter Property="Margin" Value="0" />
</Style>
</RichTextBox.Resources>
</RichTextBox>
</ScrollViewer>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.