我试图在一个;RichEditBox中获取并设置富文本,但是每次我执行一个GetText (然后是一个SetText )时,都会添加一个额外的回车。这里是一个超级简单的例子,有一个按钮,然后设置。试一试,每次执行Get设置时,都会添加一个额外的回车。
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中都尝试了各种选项,但是我能够防止插入额外的回车。有人有什么建议吗?
发布于 2018-10-07 15:30:26
最后我找到了一个合理的解决办法。我正在获取完整的文本,然后在范围上调用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;
}发布于 2020-10-31 04:28:20
我找到了一个解决方案,它似乎与列表没有冲突,也不涉及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 = "";发布于 2018-10-07 15:34:44
与此同时,我找到了另一个解决办法,但你的解决办法就没那么麻烦了:-)。我只需删除最后添加的换行符:
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的“错误”行为,所以您的解决方案要好得多。
https://stackoverflow.com/questions/52689533
复制相似问题