复制UWP RichEditBox内容会增加额外的行

时间:2018-10-07 14:38:13

标签: uwp richtextbox uwp-xaml rtf

我试图在; RichEditBox中获取并设置富文本格式,但是每次我执行GetText然后执行SetText时,都会添加一个额外的回车符。 这是一个带有按钮的超简单示例,该按钮不会被设置。尝试一下,每次执行Get-Set时都会看到一个额外的回车符。

XAML

<StackPanel>
    <Button Content="Get-Set" Click="OnGetSet"/>
    <RichEditBox x:Name="RichEditor" Width="300" Height="200"/>
</StackPanel>

C#

private void OnGetSet(object sender, RoutedEventArgs e)
{
    RichEditor.Document.GetText(TextGetOptions.FormatRtf, out value);
    RichEditor.Document.SetText(TextSetOptions.FormatRtf, value);
} 

我在SetText和GetText中都尝试了各种选项,但是我能够防止插入额外的回车符。 有人有建议吗?

3 个答案:

答案 0 :(得分:2)

我最终找到了一个合理的解决方法。我正在获取全部文本,然后在该范围而不是文档上调用GetText。

我不确定这是否是最好的解决方案,但是效果很好。

更新的C#

private void OnGetSet(object sender, RoutedEventArgs e)
{
    var value = GetText(RichEditor);
    RichEditor.Document.SetText(TextSetOptions.FormatRtf, value);
}

public string GetText(RichEditBox editor)
{
    // get the actual size of the text
    editor.Document.GetText(TextGetOptions.UseLf, out string text);

    // get the text in the total range - to avoid getting extra lines
    var range = editor.Document.GetRange(0, text.Length);
    range.GetText(TextGetOptions.FormatRtf, out string value);

    // return the value
    return value;
}

答案 1 :(得分:0)

同时,我找到了另一种解决方法,但是您的解决方法不太hacky :-)。我只是删除最后添加的换行符:

RichEditor.Document.GetText(TextGetOptions.FormatRtf, out var value);
var lastNewLine = value.LastIndexOf("\\par", StringComparison.Ordinal);
value = value.Remove(lastNewLine, "\\par".Length);
RichEditor.Document.SetText(TextSetOptions.FormatRtf, value);            

但这取决于RichEditBox的“错误”行为,因此您的解决方案要好得多。

答案 2 :(得分:0)

我为此找到了一种解决方案,该解决方案似乎与列表没有冲突,并且不涉及任何形式的RTF文本手动清除。

从ClaudiaWey的答案中可以看出,以纯文本格式获取文本时,文本长度是正确的,至少在使用LF时是如此。仅在RTF中获取文本时才会出现该问题。

所以我的解决方案是将非RTF长度与RTF文本内容一起存储,然后在将RTF内容重新加载到文本框中时删除该长度与新(错误)长度之间的差异。

以代码形式,看起来像这样:

TextBox.TextDocument.GetText(TextGetOptions.FormatRtf, out string savedRichText);
TextBox.TextDocument.GetText(TextGetOptions.UseLf, out string savedText);
var savedLength = savedText.Length;

// persist savedLength to the database or wherever alongside savedRichText...

TextBox.TextDocument.SetText(TextSetOptions.FormatRtf, savedRichText);
// Delete the extra bit that gets added because of a bug
TextBox.TextDocument.GetText(TextGetOptions.UseLf, out string text);
TextBox.TextDocument.GetRange(savedLength, text.Length).Text = "";
相关问题