【问题标题】:How to format plain text in WPF RichTextBox如何在 WPF RichTextBox 中格式化纯文本
【发布时间】:2010-09-14 01:22:04
【问题描述】:

我使用 WPF 开发了一个小型聊天客户端。在每个聊天窗口中,它包含一个显示以前聊天对话的富文本框和一个带有发送按钮的文本框,用于输入聊天消息。 我想格式化richtextbox中的显示文本,如下所示。

user1: chat message goes here

目前,我使用 AppendText 函数将聊天对话附加到richtextbox。我的代码是这样的,

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

但是通过这种方式,我找不到如上所示格式化文本的方法。有没有办法做到这一点?或任何替代方法?

谢谢

【问题讨论】:

    标签: wpf format richtextbox append


    【解决方案1】:

    您可以直接与 FlowDocument 交互以添加富文本,而不是与 RichTextBox 交互。将 RichTextBox 上的 Document 设置为包含 Paragraph 的 FlowDocument,并在 Paragraph 中添加RunBoldInline 对象。您可以通过在段落或内联上设置属性来格式化文本。例如:

    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());
    }
    

    【讨论】:

    • 干得好。好的!我测试了这段代码,它工作正常。这正是我要找的。非常感谢 Quartermeister。
    猜你喜欢
    • 2011-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多