2016-07-24 54 views
1

添加新的模塊,我想一個新的正常Run添加到RichTextBlock,如果詞不匹配,如果匹配的文本應該大膽: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循環,所以它經常重複。

回答

0

如果你看一個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); 
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 })); 
} 
+0

'「段落不包含帶1個參數的構造函數」',那就是錯誤'段落'拋出 –