如何从 c++ winrt UWP 应用程序中的代码将文本添加到 RichTextBlock,

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

给定 xaml 类似

的代码

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

如何从后面的 C++ 代码向名为 richb 的 RichTextBlock 添加文本?​​

如果它是一个 TextBlock,它就是

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

然而,这不适用于 RichTextBlock。

RichTextBlock 与 TextBlock 不同,您需要使用 Paragraph 元素来定义要在 RichTextBlock 控件中显示的文本块。关于更多信息,你可以参考这个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);