更新时间:2022-06-19 07:39:54
您可以在< TextBlock>中指定文本子集的颜色。或< RichTextBlock>使用< Run>元素:
You can specify the color of a subset of the text in a <TextBlock> or <RichTextBlock> using the <Run> element:
<TextBlock>
<Run Text="Hi" Foreground="Black">
<Run Text="my" Foreground="Black">
<Run Text="name" Foreground="Black">
<Run Text="is" Foreground="Black">
<Run Text="Rohith" Foreground="Red"><Run Text="." Foreground="Black">
</TextBlock>
您可以使用数据绑定动态构建它。
You can use data binding to build this dynamically.
谢谢Matt T Heffron的解决方案。以下是我在代码背后的做法
Thanks Matt T Heffron for the solution. Here is how I did it on code behind
FlowDocument fldoc = generateFlowDocument(MyList);
richTextBox.Document = fldoc;
private FlowDocument generateFlowDocument(List<Tuple<String,int>> MyList)
{
FlowDocument fd = new FlowDocument();
System.Windows.Documents.Paragraph para = new System.Windows.Documents.Paragraph();
foreach (Tuple<String,int> word in MyList)
{
Run run = new Run(word.Item1 + " ");
run.Foreground = returnBrushColour(word.Item2);
para.Inlines.Add(run);
}
fd.Blocks.Add(para);
return fd;
}
private Brush returnBrushColour(int colour)
{
if (colour == 1)
{
return Brushes.Black;
}
else if (colour == 2)
{
return Brushes.Red;
}
//this goes on for a while but i guess you should get the idea
}