2010-09-14 186 views
1

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

USER1:chat message goes here

暂时,我用AppendText通过函数来​​聊天对话追加到RichTextBox中。我的代码看起来像这样,

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

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

感谢

回答

5

而是与RichTextBox的互动的,你可以用的FlowDocument直接交互添加丰富的文字。将RichTextBox上的文档设置为包含段落的FlowDocument,并在段落中添加Inline对象,例如RunBold。您可以通过在段落或内联上设置属性来设置文本的格式。例如:

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

伟大的工作。太好了!我测试了这段代码,它工作正常。这正是我寻找的。非常感谢Quartermeister。 – 2010-09-14 03:21:16