C#中的XAML到Rtf的转换?

时间:2014-04-24 13:02:02

标签: c# .net wpf xaml mvvm

.NET 4,WPF MVVM。我正在尝试使用此converter 从Xaml转换回Rtf以显示在RichTextBox

以下是传递给我的方法的Xaml字符串参数的示例:

<FlowDocument xml:space="preserve" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"><Section TextAlignment="left" FontWeight="normal" FontStyle="normal" FontSize="12px" FontFamily="segoe ui" Foreground="#000000"><Paragraph FontSize="14px" FontFamily="arial" Margin="0"><Span><Run>Test body.</Run></Span></Paragraph><List MarkerStyle="Disc" Margin="0" Padding="0"><ListItem><Paragraph FontSize="14px" FontFamily="arial" Margin="0"><Span><Run>Bullet 1</Run></Span></Paragraph></ListItem><ListItem><Paragraph FontSize="14px" FontFamily="arial" Margin="0"><Span><Run>Bullet 2</Run></Span></Paragraph></ListItem></List><Paragraph FontSize="14px" FontFamily="arial" Margin="0"><Span><Run>Back to text.</Run></Span></Paragraph></Section></FlowDocument>

这是我的viewModel中的XamlToRtf方法:

private string ConvertXamlToRtf(string richTextBoxText)
{
    var richTextBox = new System.Windows.Controls.RichTextBox();
    if (string.IsNullOrEmpty(richTextBoxText))
    {
        return "";
    }

    var textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd);

    using (var xamlMemoryStream = new MemoryStream())
    {
        using (var xamlStreamWriter = new StreamWriter(xamlMemoryStream))
        {
            xamlStreamWriter.Write(richTextBoxText);
            xamlStreamWriter.Flush();
            xamlMemoryStream.Seek(0, SeekOrigin.Begin);

            textRange.Load(xamlMemoryStream, DataFormats.Xaml);
        }
    }

    using (var rtfMemoryStream = new MemoryStream())
    {
        textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); 
        textRange.Save(rtfMemoryStream, DataFormats.Rtf);
        rtfMemoryStream.Seek(0, SeekOrigin.Begin);
        using (var rtfStreamReader = new StreamReader(rtfMemoryStream))
        {
            return rtfStreamReader.ReadToEnd();
        }
    }
}

Xaml被传递到文本范围,但是在textRange.Load(xamlMemoryStream, DataFormats.Xaml);行,文本被从textRange中剥离出来,最后我得到了一个空的Rtf shell,FlowDocument Xaml标签仍然包含在这样:

<FlowDocument>{\rtf1\ansi\ansicpg1252\uc1\htmautsp\deff2{\fonttbl{\f0\fcharset0 Times New Roman;}{\f2\fcharset0 Segoe UI, Lucida Sans Unicode, Verdana;}}{\colortbl\red0\green0\blue0;\red255\green255\blue255;}\loch\hich\dbch\pard\plain\ltrpar\itap0{\lang1033\fs18\f2\cf0 \cf0\ql{\f2 \li0\ri0\sa0\sb0\fi0\ql\par}
}}</FlowDocument>

DataFormats.Xaml无法识别我的某些Xaml代码,不知道为什么它会删除所有文本?

由于

1 个答案:

答案 0 :(得分:1)

TextRange显然不能是FlowDocument本身,例如只有Section

这意味着,您不应将您的XAML输入包装在<FlowDocument>中,而只需使用<Section>