user3821206
user3821206

Reputation: 619

Set Text to the RichTextBlock in code behind

I am trying to set Text to a RichTextBlock in a universal app,this is my code in xaml:

<RichTextBlock x:Name="descr">
       <Paragraph>
             <Paragraph.Inlines>
                 <Run Text="{Binding Path=desc}"/>
             </Paragraph.Inlines>
       </Paragraph>
</RichTextBlock>

but I dont know how to set Text in this RichTextBlock in code behind,this is my try:

Paragraph p = new Paragraph();
  p.Inlines.Add("test");//error here cannot convert from 'string' to 'Windows.UI.Xaml.Documents.Inline' 
  descr.Blocks.Add(p);

so how can I set Text to the RichTextBlock in code behind C# thanks for help

Upvotes: 2

Views: 4363

Answers (1)

Mehrzad Chehraz
Mehrzad Chehraz

Reputation: 5137

The Inlines property is an InlineCollection which is a collection of Inline objects, while you are trying to add a string to this collection.

MSDN for Inline

Provides a base class for inline text elements, such as Span and Run.

So you need to add either a Run or Span object instead.

// Create run and set text
Run run = new Run();
run.Text = "test";

// Create paragraph
Paragraph paragraph = new Paragraph();

// Add run to the paragraph
paragraph.Inlines.Add(run);

// Add paragraph to the rich text block
richTextBlock.Blocks.Add(paragraph);

Edit

Seems like you cannot directly bind Text property of a Run or Span object from the code behind.

Upvotes: 5

Related Questions