我有一个方法可以设置文本范围和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" 也许这有什么问题?
答案 0 :(得分: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);
答案 1 :(得分:0)
我更改了range.Load以使用DataFormats.Text,它现在考虑了换行符。