views:

71

answers:

1

hi everyone,

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.

user1: chat message goes here

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?

thanks

+1  A: 

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());
}
Quartermeister
great work. nice! I test this code and it works correctly. This is exactly what i looking for. thank you very much Quartermeister.
arlahiru