如何使用RichEditBox提供格式化文本

How to use RichEditBox to provide formatted text

根据 Microsoft 的 Quickstart: adding text input and editing controls, I should use RichEditBox,我应该提供某种格式化的文本编辑器。不幸的是,他们在示例中非常节俭。提供的示例仅显示如何加载 RTF 文件以进行显示。它没有说明如何允许用户操作文档。例如,我想添加 BI 等典型的格式设置按钮,让用户更改 upcoming/selected 文本的格式。但是我应该怎么做才能处理来自软件键盘的用户输入呢?我的想象是键盘提供 "raw" 字符输入,我需要正确检测和应用样式。

只要我有办法对用户输入做出反应,下一个问题就是以编程方式更新基础文档。假设我想将用户选择更改为一些新文本。

 // Change selected text; let assume I magically get the text whose format I should update and add necessary RTF stuffs; for testing, can use

 String^ newText = "{\rtf1\ansi{\fonttbl\f0\fswiss Helvetica;}\f0\par\n{\b bold}\par}";
 mRichEditBox->Document->Selection->SetText(TextSetOptions::FormatRtf, newText);

 // After the above line, mRichEditBox loses focus & the keyboard is dismissed so I attempt to focus it programmatically & bring back the keyboard.

 Editor->Focus(Windows::UI::Xaml::FocusState::Keyboard);

 // By default, after SetText, the updated text will be selected, this will put the cursor after changed text; so user can continue adding text

 mRichEditBox->Document->Selection->Collapse(false);

让我们暂时原谅烦人的 UI 反复带键盘 up/down 的问题:例如用户按下 t,我通过上面的代码使 t 加粗,系统自动关闭键盘,代码将其恢复,并将光标放在 之后t,用户可以按e,我通过上面的代码把e加粗,系统自动关闭键盘,代码把它带回来,然后放e 之后的光标等。每次 RichEditBox 进入 out/in 焦点时,由于 RichEditBox 的背景颜色发生变化,屏幕会闪烁。你猜这个故事。但这可能是因为我暂时使用按钮触发更改。

更严重的问题是对焦问题:有时会带回键盘,有时又不会。即使它确实带回了键盘,键盘现在也变得不复存在了:按键不再插入文本,就好像键盘失去了目标一样!?更糟糕的是:我的 phone 在执行这些程序化替换几次后重新启动!

任何人都可以确认这是一个现有的 OS 问题,或者我是否可以做些什么来解决它?

您不需要将自己的 RTF 插入到 RichEditBox 中。通常,您只会在保存或恢复 REB 时这样做。

要更改所选内容的字符属性(例如颜色、粗体、斜体等),请获取所选范围并更新其 CharacterFormat。添加到该范围内的新文本将继承其周围的格式,因此当用户不断键入时,新文本将自动遵循之前的格式。应用程序不应尝试猜测 InputPane 的打开和关闭。

有关详细信息,请参阅 MSDN Xaml text editing sample 中的场景 6。这是一个快速预览:

void Scenario6::BoldButtonClick(Object^ sender, RoutedEventArgs^ e) 
{ 
    ITextSelection^ selectedText = editor->Document->Selection; 
    if (selectedText != nullptr) 
    { 
        ITextCharacterFormat^ charFormatting = selectedText->CharacterFormat; 
        charFormatting->Bold = FormatEffect::Toggle; 
        selectedText->CharacterFormat = charFormatting; 
    } 
}