【问题标题】:RichTextBox make text multiple coloursRichTextBox 使文本具有多种颜色
【发布时间】:2020-06-22 16:32:32
【问题描述】:

我目前正在使用 C# WPF 开发一个消息传递应用程序。我正在尝试将文本插入到 RichTextBox 中,但在一行上应用不同的颜色。

[Billy123] The message

我希望文本显示在一行上,如图所示,并以一种颜色(即:红色)显示用户名(在括号中),然后以另一种颜色显示消息,即:黑色。

我尝试了以下两次:

run.Foreground = new SolidColorBrush(Colors.Red); // My Color
Paragraph paragraph = new Paragraph(run);
MyRichTextBlock.Document.Blocks.Add(paragraph);

但这会将单独的文本显示为两部分,而我需要它们在一行上。

我也试过了:

 currentChatDisplay.AppendText("Loren");
            currentChatDisplay.Foreground = new SolidColorBrush(currentUserMessageColour);
            currentChatDisplay.AppendText("Loren");

(currentChatDisplay 是 RichTextBox 的名称)但它改变了所有文本的颜色。

我将如何实现这一目标?

编辑:我已经采用了 @Peregrene 在 cmets 中演示的方法

【问题讨论】:

  • 必须是富文本吗?我创建了一个增强的 TextBlock 控件,该控件将允许使用类似于文本中的 HTML 的标签根据需要设置任何文本属性,包括前景色和背景色 - peregrinesview.uk/wpf-controls-formatted-textblock
  • @Peregrine 我查看了您的网页,它非常适合我的应用程序!我可能会选择这种方法,因为我更喜欢使用 HTML 语法进行格式化。

标签: c# .net wpf


【解决方案1】:

以下内容对我有用,我的 rtb 名称为 MyRichTextBox:

TextRange userName = new TextRange(MyRichTextBox.Document.ContentEnd, MyRichTextBox.Document.ContentEnd);
        userName.Text = "[Billy123] ";
        userName.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Red);

        TextRange text = new TextRange(MyRichTextBox.Document.ContentEnd, MyRichTextBox.Document.ContentEnd);
        text.Text = "The message";
        text.ApplyPropertyValue(TextElement.ForegroundProperty, Brushes.Black);

【讨论】:

  • 这太完美了!但是,我已经使用了 cmets 中的自定义控件
【解决方案2】:

如果您只想显示彩色文本,则不需要繁重的RichTextBox。只需使用TextBlock 并使用TextBlock.Inlines 设置内容。
您通常会使用常见的TextBox 作为输入。然后将此输入添加到彩色消息视图中,这是一个 ListBox,它为每个项目(即消息条目)显示一个 TextBlock。

XAML

<TextBlock x:Name="ColoredTextBlock">
  <TextBlock.Inlines>
    <Run Text="Red text. " Foreground="Red" />
    <Run Text="Green text." Foreground="Green" />
  </TextBlock.Inlines>
</TextBlock>

C#

var coloredTextBlock = new TextBlock();
coloredTextBlock.Inlines.Add(new Run("Red text. ") { Foreground = Brushes.Red });
coloredTextBlock.Inlines.Add(new Run("Green text. ") { Foreground = Brushes.Green });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-16
    • 2014-01-28
    • 1970-01-01
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 2012-03-06
    • 1970-01-01
    相关资源
    最近更新 更多