本文介绍了如何在WPF RichTextBox的格式化纯文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在使用WPF开发的小型聊天客户端。在每一个聊天窗口,它包含一个RichTextBox显示previous聊天对话,并发送按钮一个文本框输入聊天信息。
我想在RichTextBox中显示文本的格式如下图所示。

I have developed a small chat client using WPF. In each chat window, it contains a richtextbox to display previous chat conversations and a textbox with send button to type a chat message.I want to format the display text in the richtextbox as shown below.

用户1: 聊天信息放在这里

有关目前,我用AppendText通过函数来​​聊天对话追加到RichTextBox中。我的code是这样的,

For the time being, I use AppendText function to append chat conversation to the richtextbox. my code looks like this,

this.ShowChatConversationsBox.AppendText(from+": "+text);

但这种方式,我找不到格式化文本如上显示的方法。有没有办法做到这一点?或任何其他方法?

But in this way, i couldn't find a method to format the text as show above. Is there any way to do this? or any alternative methods?

感谢

推荐答案

而不是用RichTextBox的互动,你可以与FlowDocument的直接交互添加丰富的文本。设置包含段落在RichTextBox一个FlowDocument的文档,并添加或的的段落。您可以通过设置在章节或上内联属性设置文本的格式。例如:

Instead of interacting with the RichTextBox, you can interact with the FlowDocument directly to add rich text. Set the Document on the RichTextBox to a FlowDocument containing a Paragraph, and add Inline objects such as Run or Bold to the Paragraph. You can format the text by setting properties on the Paragraph or on the Inlines. For example:

public MainWindow()
{
    InitializeComponent();
    this.paragraph = new Paragraph();
    this.ShowChatConversationsBox.Document = new FlowDocument(paragraph);
}

private Paragraph paragraph;

private void Button_Click(object sender, RoutedEventArgs e)
{
    var from = "user1";
    var text = "chat message goes here";
    paragraph.Inlines.Add(new Bold(new Run(from + ": "))
    {
        Foreground = Brushes.Red
    });
    paragraph.Inlines.Add(text);
    paragraph.Inlines.Add(new LineBreak());
}

这篇关于如何在WPF RichTextBox的格式化纯文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 13:10
查看更多