Search code examples
c++xamluwpc++-winrt

How Can I add Text to a RichTextBlock from the code behind in a c++ winrt UWP app,


Given xaml code like


<RichTextBlock x:Name="richb"> </RichTextBlock>

How can I add text to the RichTextBlock named richb from the c++ code behind?

If it were a TextBlock it would just be

richb().Text(L"Any text can go here");

However this does not work for a RichTextBlock.


Solution

  • RichTextBlock is different from TextBlock, you need to use Paragraph elements to define the blocks of text to display within a RichTextBlock control. About more information, you can refer to this document.

    #include "winrt/Windows.UI.Xaml.Documents.h"
    
    using namespace winrt;
    using namespace Windows::UI::Xaml;
    using namespace Windows::UI::Xaml::Documents;
    
    
    Paragraph paragraph = Paragraph();
    Run run = Run();
    
    // Customize some properties on the RichTextBlock.
    richb().IsTextSelectionEnabled(true);
    richb().TextWrapping(TextWrapping::Wrap);
    run.Text(L"This is some sample text to show the wrapping behavior.");
    
    // Add the Run to the Paragraph, the Paragraph to the RichTextBlock.
    paragraph.Inlines().Append(run);
    richb().Blocks().Append(paragraph);