2010-09-14 59 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