RichTextBlock在循环中添加新块

时间:2016-07-24 08:14:31

标签: c# uwp richtextbox windows-10-universal

我想向Run添加一个新的正常RichTextBlock,如果该字词不匹配,如果匹配,则该字词应为粗体:

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循环中,所以它经常重复。

2 个答案:

答案 0 :(得分:1)

如果查看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);

您可以创建ParagraphRun个对象,检查文字是否必须为粗体,然后将其添加到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);

答案 1 :(得分:0)

我认为你可以简单地解决你的问题:

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