【问题标题】:Injecting XAML into a RichEditBox将 XAML 注入 RichEditBox
【发布时间】:2023-03-08 07:47:01
【问题描述】:

我目前正在尝试将 Matthew Manela 的 "Converting between RTF and XAML" 代码示例移植到 WinRT

我已经让 HTML 到 XAML 代码正常工作,但是在将其放入 RichEditBox 时遇到了问题。

Matthew 的代码基于 WPF,并使用以下函数将 XAML 转换为 RTF。

private static string ConvertXamlToRtf(string xamlText) 
{ 
    var richTextBox = new RichTextBox(); 
    if (string.IsNullOrEmpty(xamlText)) return ""; 
    var textRange = new TextRange(richTextBox.Document.ContentStart, richTextBox.Document.ContentEnd); 
    using (var xamlMemoryStream = new MemoryStream()) 
    { 
        using (var xamlStreamWriter = new StreamWriter(xamlMemoryStream)) 
        { 
            xamlStreamWriter.Write(xamlText); 
            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(); 
        } 
    } 
}

我尝试在 WinRT 中使用 RichEditBox 重写此代码,但遇到了一些问题。最值得注意的是,WPF TextRange 接受 XAML 数据格式,但 WinRT ITextRange 没有这个。但是,我知道我可以将 XAML 直接注入到 RichTextBlock 控件中。

有没有办法以编程方式从RichTextBlock 复制文本并将其粘贴到 RichEditBox 中?

OR,如果失败了,有没有办法将 HTML 转换为在 WinRT/Windows 应用商店应用程序中工作的 RTF?

【问题讨论】:

  • 只有一条评论。不是同样的问题,但可能会有所启发。 underground.infovark.com/2011/03/03/…
  • 同样不一样,但可能会有所帮助stackoverflow.com/questions/3728584/…
  • 谢谢,不过我在突出显示内容方面没有问题,这在 RichEditBox 或 RichTextBlock 中都很容易。我只是无法将内容从一个移动到另一个。
  • Check this sample out。它描述了如何将 HTML 转换为 RTF,但使用的是 RichTextBlock。不过,您可以尝试使用他的方法。另一个示例是 here,似乎更符合您的要求。
  • 您可能还想查看HtmlAgilityPack

标签: c# wpf xaml windows-runtime windows-store-apps


【解决方案1】:

我在 msdn Windows 应用论坛上从 Rob Caplan 那里得到了答案

http://social.msdn.microsoft.com/Forums/windowsapps/en-US/c5f4e679-c563-463c-b812-05b16cd5720f/converting-html-to-rtf-using-richeditbox-and-richtextbox?forum=winappswithcsharp

直接引用:

"您必须自己进行转换。RichEdiBox 没有任何本机转换能力。它直接呈现 RTF 而不会将其转换为 Xaml。这与 WPF 实现不同,后者转换 RTF 而不是直接显示。”

嗯,就是这样。我目前正在调整一个开源 RTF 库以供 WinRT 使用。完成后我会发布。

编辑

罗伯错了!这可能的,尽管通过一种变通方法。我想出了如何使用DataPackage 类来做到这一点。完整答案在这里:https://stackoverflow.com/a/22093837/352867

【讨论】:

  • 如果HTML中包含图像则不起作用。
  • @Shefali 我猜这取决于图像的来源,以及它们是否具有绝对路径等。可以将 src 中的相对路径转换为绝对路径,然后复制
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-12-30
  • 1970-01-01
  • 2010-10-28
相关资源
最近更新 更多