Using richtextbox as a chat window which displays

2019-09-06 00:01发布

问题:

I am making a C# WPF chat messenger, i have used Wpf rich text box for displaying chat, but i am trying to customize nick and do some text alignment, rich text box having text is made by appending text using code, i dont know how to customize it, i am attaching an image for more explanation

I want this date to be left aligned, and i want the nick name should be blue in color. I think we cannot use HTML Text in rich text box, or whats the solution for customizing the text, should i use some tags, or what, please let me know the better solution.

回答1:

You may be better served by using a FlowDocument and appending to the document's content as each message is sent/received (click for more info).



回答2:

I thought that in code you have to use /b for bold. So in this case, your code would be like

rtextbox.Text = "/bHello/b";

Let me know if it worked.

Edit because the first solution didn't work :

1 Select the text that you want to transform :

rtb.select(Start , Length of string)

2 Create a font with the right properties and add it to the selection

rtb.Selectionfont = new Font(rtb.SelectionFont, FontStyle.Bold)


回答3:

Create a new Span every time and add it instead of appending text.

            Span nick = new Span();
            nick.Foreground = Brushes.Blue;

            Span date = new Span();
            date.FontWeight = FontWeights.Bold;

            Paragraph para = new Paragraph();
            para.Inlines.Add(nick);
            para.Inlines.Add(date);

            FlowDocument d = new FlowDocument();
            d.Blocks.Add(para);

            rtb.Document = d;

Hope this helps.

Regards,

Jawahar