加载RichTextbox时,请转换RTF。
using (var stream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(rtfString)))
{
TargetRichTextBox.Selection.Load(stream, DataFormats.Rtf);
}
public string ConvertRichTextBoxToRtf(RichTextBox richTextBox)
{
if (richTextBox == null) throw new ArgumentNullException(nameof(richTextBox));
using (var memoryStream = new System.IO.MemoryStream())
{
var range = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);
range.Save(memoryStream, DataFormats.Rtf);
return System.Text.Encoding.UTF8.GetString(memoryStream.ToArray());
}
}
public void SetSelectionToSubscript(TextRange range)
{
if (range.IsEmpty) return; // Don't apply formatting to an empty selection
object currentBaseline = range.GetPropertyValue(Inline.BaselineAlignmentProperty);
if (currentBaseline is BaselineAlignment alignment && alignment == BaselineAlignment.Subscript)
{
// Reset to normal text
range.ApplyPropertyValue(Inline.BaselineAlignmentProperty, BaselineAlignment.Baseline);
range.ApplyPropertyValue(TextElement.FontSizeProperty, MyFondSize); // Reset font size
}
else
{
// Apply subscript formatting
range.ApplyPropertyValue(Inline.BaselineAlignmentProperty, BaselineAlignment.Subscript);
range.ApplyPropertyValue(TextElement.FontSizeProperty, MyFondSize - 2); // Adjust font size for subscript effect
}
}
您的代码正确。不幸的是,WPF
RichTextBox
RTF格式规范中描述的许多格式。
在进行解决方案时,您可以在保存/加载文档时使用DataFormats.Xaml
或