[英]WPF RichTextBox: How to add different colors in a single sentence in Run(text)?
I have a client talking to a server. 我有一个客户正在与服务器交谈。 The server may may send back the buffer as "Bob: Is anyone here?" 服务器可能将缓冲区发送回为“鲍勃:有人在吗?” You can think of it like a chatroom. 您可以将其视为聊天室。
Prior to the first occurrence of ':', I would like to make this word green. 在第一次出现“:”之前,我想将此词设为绿色。 Everything to the right of ':' will stay white. ':'右边的所有内容将保持白色。
How can I do this? 我怎样才能做到这一点? I found this not to be so straight-forward. 我发现这不是那么简单。
This writes an incoming text message to the RichTextBox: 这会将传入的文本消息写入RichTextBox:
public void WriteLine(string text)
{
Paragraph para = new Paragraph();
// Buffer output
para.Inlines.Add(new Run(text));
// Add block
txtOutput.Document.Blocks.Add(para);
// Always keep scrolled to the end
txtOutput.ScrollToEnd();
// Clear input field.
txtInput.Clear();
// Focus back on the input field.
txtInput.Focus();
}
My attempt: 我的尝试:
// Output buffer
para.Inlines.Add(new Run { Text = text, Foreground = Brushes.Green, FontWeight = FontWeights.Bold });
The problem with doing it this way is the whole line will be green. 这样做的问题是整条线都是绿色的。 What I need is this format: 我需要的是这种格式:
Name (Green): Output (White). 名称(绿色):输出(白色)。
Please let me know. 请告诉我。 Thanks. 谢谢。
Prior to the first occurrence of ':', I would like to make this word green. 在第一次出现“:”之前,我想将此词设为绿色。 Everything to the right of ':' will stay white. ':'右边的所有内容将保持白色。
Based on your requirement in question, all you need to do is to split the text and add two Run to your Paragraph. 根据您的需求,您所需要做的就是拆分文本并将两个Run添加到您的段落中。
Check the below code. 检查以下代码。
public void WriteLine(string text)
{
Paragraph para = new Paragraph();
//Split the content from text
var content = text.Split(':');
// Buffer output
para.Inlines.Add(new Run { Text = content[0] + ": ", Foreground = Brushes.Green, FontWeight = FontWeights.Bold });
para.Inlines.Add(new Run { Text = content[1], Foreground = Brushes.White, FontWeight = FontWeights.Regular });
// Add block
txtOutput.Document.Blocks.Add(para);
// Always keep scrolled to the end
txtOutput.ScrollToEnd();
//// Clear input field.
//txtInput.Clear();
//// Focus back on the input field.
//txtInput.Focus();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.