Reputation: 451
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
Upvotes: 1
Views: 5683
Reputation: 59129
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());
}
Upvotes: 5