【发布时间】:2018-10-01 09:32:46
【问题描述】:
我有一个方法可以设置文本范围和 rtf 字符串。我的问题是在将其加载到 TextRange 时,它会丢失换行符。当我从内存流加载 rtf 字符串时,如何确保我的换行符存在?目前我的方法如下:
public static void LoadRtf(string rtf, TextRange range)
{
if (string.IsNullOrEmpty(rtf))
return;
using (MemoryStream rtfMemoryStream = new MemoryStream())
{
using (StreamWriter rtfStreamWriter = new StreamWriter(rtfMemoryStream))
{
rtfStreamWriter.Write(rtf);
rtfStreamWriter.Flush();
rtfMemoryStream.Seek(0, SeekOrigin.Begin);
range.Load(rtfMemoryStream, DataFormats.Rtf);
}
}
}
扩展 RichTextBox 的调用类
public class RtfBox : RichTextBox
{
public object RtfContent
{
get { return GetValue(RtfContentProperty); }
set { SetValue(RtfContentProperty, value); }
}
public static readonly DependencyProperty RtfContentProperty =
DependencyProperty.RegisterAttached("RtfContent", typeof(object), typeof(RtfBox),
new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsRender, RtfContentChanged));
static void RtfContentChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs evt)
{
RtfBox box = depObj as RtfBox;
if (box == null)
return;
string sContent = evt.NewValue as string;
if (sContent == null)
{
byte[] bContent = evt.NewValue as byte[];
if (bContent != null)
sContent = Encoding.UTF8.GetString(bContent);
}
box.Document.Blocks.Clear();
try
{
TextRange range = new TextRange(box.Document.ContentStart, box.Document.ContentEnd);
FlowDocumentRtfConverter.LoadRtf(sContent, range);
if (box.Document.FontStyle == FontStyles.Normal)
box.Document.FontStyle = box.FontStyle;
if (box.Document.FontWeight == FontWeights.Normal)
box.Document.FontWeight = box.FontWeight;
if (box.Document.FontStretch == FontStretches.Normal)
box.Document.FontStretch = box.FontStretch;
}
catch (Exception e)
{
}
}
public RtfBox()
: base()
{
IsDocumentEnabled = false;
}
}
我当前使用的 rtf 字符串值是“H\0e\0l\0l\0o\0\r\0\n\02\0n\0d\0 \0l\0i\0n\0e\0\ r\0" 也许这有什么问题?
【问题讨论】:
标签: c# rtf memorystream