C# 将rtf字符串加载到TextRange中不包括换行符
我有一个方法,可以设置文本范围从和rtf字符串。我的问题是,当加载到TextRange时,它会丢失换行符。当我从内存流加载rtf字符串时,如何确保换行符在那里?目前我的方法如下:C# 将rtf字符串加载到TextRange中不包括换行符,c#,rtf,memorystream,C#,Rtf,Memorystream,我有一个方法,可以设置文本范围从和rtf字符串。我的问题是,当加载到TextRange时,它会丢失换行符。当我从内存流加载rtf字符串时,如何确保换行符在那里?目前我的方法如下: public static void LoadRtf(string rtf, TextRange range) { if (string.IsNullOrEmpty(rtf)) return; using (MemoryStream rtfMem
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”
也许这有什么问题?我尝试了你的代码,只做了如下的轻微修改,它对我很有效。也许这就是你初始化文本范围的方式
public static string 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);
}
}
return range.Text;
}
然后我调用了这段代码,返回的字符串有换行符,并在富文本框控件中正确显示
string rtf = File.ReadAllText(@"c:\temp\document.rtf");
FlowDocument flowDocument = new FlowDocument();
TextRange range = new TextRange(flowDocument.ContentStart, flowDocument.ContentEnd);
this.richTextBox1.Text = LoadRtf(rtf, range);
我将range.Load更改为使用DataFormats.Text,现在它考虑了换行符。我添加了调用类,如果这样可以提供一些更有用的信息的话。在我这方面仍然没有运气。我改变了范围。加载使用数据格式。文本,现在它考虑到换行符