在 UWP 中合并两个 RTF

Merging two RTFs in UWP

我有两个字符串 (RTF),我必须以某种方式合并它们 - 在两者之间插入一个新行 - 以显示在 UWP 的 RichEditBox 中。我已经阅读了一种解决方法,其中通过使用两个 RichTextBox 控件来合并两者,但在 UWP 中,这并不是一个真正的选项(而且我也无法在两个 RichEditBox 控件中显示两个 RTF)。有没有不使用第三方库的替代方法?

在使用RichEditBox class时,我们可以利用 ITextDocument interface and ITextRange interface。以下是一个简单的示例:

var rtf1 = @"{\rtf1{\fonttbl{\f0 Verdana;}{\f1 Arial;}{\f2 Verdana;}{\f3 Calibri;}}{\colortbl;\red255\green255\blue255;\red255\green0\blue0;}\f0\cf2 This is red text marked by Verdana font.\par}";

// Sets rtf1 as the content of the document
editor.Document.SetText(Windows.UI.Text.TextSetOptions.FormatRtf, rtf1);

// Get a new text range for the active story of the document.
var range = editor.Document.GetRange(0, rtf1.Length);

// Collapses the text range into a degenerate point at the end of the range for inserting.
range.Collapse(false);

var rtf2 = @"{\rtf1{\fonttbl{\f0 Times New Roman;}}{\colortbl;\red255\green255\blue255;\red0\green0\blue255;}\f0\cf2 This is blue text marked by Times New Roman font.\par}";

// Inserts rtf2
range.SetText(Windows.UI.Text.TextSetOptions.FormatRtf, rtf2);

//var newrtf = string.Empty;
//editor.Document.GetText(Windows.UI.Text.TextGetOptions.FormatRtf, out newrtf);

//System.Diagnostics.Debug.WriteLine(newrtf);

这会将 rtf2 合并到 rtf1 的末尾,并且会自动创建一个新的有效 RTF。您可以使用 ITextDocument.GetText method.

检索新的 RTF