如何在 WPF RichTextBox 中设置纯文本格式

发布于 2024-09-18 15:05:26 字数 377 浏览 1 评论 0原文

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

user1: 聊天消息在此处

目前,我使用 AppendText 函数将聊天对话附加到 Richtextbox 中。我的代码看起来像这样,

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

但是这样,我找不到格式化文本的方法,如上所示。有什么办法可以做到这一点吗?或任何替代方法?

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

瀟灑尐姊 2024-09-25 15:05:26

您可以直接与 FlowDocument 交互来添加富文本,而不是与 RichTextBox 交互。将 RichTextBox 上的文档设置为包含段落的 FlowDocument,并添加 内联对象,例如运行 或粗体到该段落。您可以通过设置段落或内联属性来设置文本格式。例如:

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

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());
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文