paragraphrichtextblock

[UWP][C#] Adding text to RichTextBlock


First of all I am completely new into both XAML and C#, so please forgive me for some stupid errors. An explanation is much more appreciated.

I've been struggling this last hours trying to figure out one of the simplest things: how to add text to a RichTextBlock when a button is pressed. I've tried some solutions that I found on Internet but none of them actually worked.

In particular it seems like there aren't the necessary references. For instance VS does not recognize the following code : Run myrun = new Run(); nor Paragraph mypar = new Paragraph(); or myrichtextblock.document.

What am I missing?


Solution

  • Check this example:

    Taken from MSDN documentation

    https://msdn.microsoft.com/library/windows/apps/br227565

    // Create a RichTextBlock, a Paragraph and a Run.
    RichTextBlock richTextBlock = new RichTextBlock();
    Paragraph paragraph = new Paragraph();
    Run run = new Run();
    
    // Customize some properties on the RichTextBlock.
    richTextBlock.IsTextSelectionEnabled = true;
    richTextBlock.TextWrapping = TextWrapping.Wrap;
    run.Text = "This is some sample text to show the wrapping behavior.";
    richTextBlock.Width = 200;
    
    // Add the Run to the Paragraph, the Paragraph to the RichTextBlock.
    paragraph.Inlines.Add(run);
    richTextBlock.Blocks.Add(paragraph);
    
    // Add the RichTextBlock to the visual tree (assumes stackPanel is decalred in XAML).
    stackPanel.Children.Add(richTextBlock);
    

    Just see how to add text in this example and modify the code to put inside of your click event of your button

    Please mark this answer if it's useful for you!

    Best Regards!