RichTextBlock 在循环中添加新块
RichTextBlock add new Blocks in loop
我想在 RichTextBlock
中添加一个新的正常 Run
,如果单词不匹配,如果匹配,文本应该是粗体:
if (InnerTextofCell == "TEXT")
{
rtb2.Blocks.Add(new Paragraph (new Run { FontWeight = FontWeights.Bold, Text = innerTextOfCell }));
}
else
{
rtb2.Blocks.Add(new Paragraph (new Run { Text = innerTextOfCell }));
}
我唯一的问题是,Paragraph
没有包含 1 个参数的构造函数。
有人有解决办法吗?
而且它在 foreach
循环中,所以它经常重复。
我想你可以简单地这样做来解决你的问题:
if (InnerTextofCell == "TEXT")
{
rtb2.Blocks.Add(new Paragraph (new Run { FontWeight = FontWeights.Bold, Text = innerTextOfCell }));
}
else
{
rtb2.Blocks.Add(new Paragraph (new Run { FontWeight = FontWeights.Normal, Text = innerTextOfCell }));
}
如果您查看 Paragraph
对象,您会注意到 Inlines
属性(您向其添加运行)是只读的。所以你不能在构造函数中添加这些。一种可能的解决方案如下:
var paragraph = new Paragraph();
var run = new Run { Text = innerTextOfCell };
if (InnerTextofCell == "TEXT")
{
run.FontWeight = FontWeights.Bold;
}
paragraph.Inlines.Add(run);
rtb2.Blocks.Add(paragraph);
您创建 Paragraph
和 Run
对象,检查文本是否必须加粗,并将它们添加到 RichTextBlock
。
既然你在谈论一个 foreach
循环,你甚至可以根据你想要的设计重新使用 Paragraph
对象(文本在一行或堆叠在多行)。您的代码将类似于:
var paragraph = new Paragraph();
foreach(...)
{
var run = new Run { Text = innerTextOfCell };
if (InnerTextofCell == "TEXT")
{
run.FontWeight = FontWeights.Bold;
}
}
paragraph.Inlines.Add(run);
rtb2.Blocks.Add(paragraph);
我想在 RichTextBlock
中添加一个新的正常 Run
,如果单词不匹配,如果匹配,文本应该是粗体:
if (InnerTextofCell == "TEXT")
{
rtb2.Blocks.Add(new Paragraph (new Run { FontWeight = FontWeights.Bold, Text = innerTextOfCell }));
}
else
{
rtb2.Blocks.Add(new Paragraph (new Run { Text = innerTextOfCell }));
}
我唯一的问题是,Paragraph
没有包含 1 个参数的构造函数。
有人有解决办法吗?
而且它在 foreach
循环中,所以它经常重复。
我想你可以简单地这样做来解决你的问题:
if (InnerTextofCell == "TEXT")
{
rtb2.Blocks.Add(new Paragraph (new Run { FontWeight = FontWeights.Bold, Text = innerTextOfCell }));
}
else
{
rtb2.Blocks.Add(new Paragraph (new Run { FontWeight = FontWeights.Normal, Text = innerTextOfCell }));
}
如果您查看 Paragraph
对象,您会注意到 Inlines
属性(您向其添加运行)是只读的。所以你不能在构造函数中添加这些。一种可能的解决方案如下:
var paragraph = new Paragraph();
var run = new Run { Text = innerTextOfCell };
if (InnerTextofCell == "TEXT")
{
run.FontWeight = FontWeights.Bold;
}
paragraph.Inlines.Add(run);
rtb2.Blocks.Add(paragraph);
您创建 Paragraph
和 Run
对象,检查文本是否必须加粗,并将它们添加到 RichTextBlock
。
既然你在谈论一个 foreach
循环,你甚至可以根据你想要的设计重新使用 Paragraph
对象(文本在一行或堆叠在多行)。您的代码将类似于:
var paragraph = new Paragraph();
foreach(...)
{
var run = new Run { Text = innerTextOfCell };
if (InnerTextofCell == "TEXT")
{
run.FontWeight = FontWeights.Bold;
}
}
paragraph.Inlines.Add(run);
rtb2.Blocks.Add(paragraph);