在FlowDocument中关注相对链接

时间:2016-12-09 14:04:01

标签: c# .net wpf flowdocument

我正在尝试在C#中使用WPF应用程序来显示包含一些相对链接的RTF文档。为了处理文档中的链接,我在网上找到了以下代码。我已验证指向www.google.com网址的链接有效。 现在的问题是RTF包含一些指向其他页面的链接,例如指向书签的链接" Pag2"。我如何让这些工作?

//Code to process the links:
using System.Windows.Documents;
using System.Collections.Generic;
using System.Windows;
using System.Linq;
using System.Diagnostics;

#region Activate Hyperlinks in the Rich Text box
static class Hyperlinks
{
//http://stackoverflow.com/questions/5465667/handle-all-hyperlinks-mouseenter-event-in-a-loaded-loose-flowdocument
public static void SubscribeToAllHyperlinks(FlowDocument flowDocument)
    {
    var hyperlinks = GetVisuals(flowDocument).OfType<Hyperlink>();
    foreach (var link in hyperlinks)
        link.RequestNavigate += new System.Windows.Navigation.RequestNavigateEventHandler(link_RequestNavigate);
    }

public static IEnumerable<DependencyObject> GetVisuals(DependencyObject root)
    {
    foreach (var child in LogicalTreeHelper.GetChildren(root).OfType<DependencyObject>())
        {
        yield return child;
        foreach (var descendants in GetVisuals(child))
            yield return descendants;
        }
    }

public static void link_RequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
    {
    //http://stackoverflow.com/questions/2288999/how-can-i-get-a-flowdocument-hyperlink-to-launch-browser-and-go-to-url-in-a-wpf
    if (e.Uri.IsAbsoluteUri)
        {
        Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
        }
    else
        {
        // code to navigate to relative uri such as #Page2??
        }
    e.Handled = true;
    }
}
#endregion Activate Hyperlinks in the Rich Text box

//Calling code:
class FlowDocTest_VM
    {
    public FlowDocTest_VM()
        {
            string filename = "D:\\Manual.rtf";
            fdContent = new FlowDocument();
            FileStream fsHelpfile = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
            TextRange trContent = new TextRange(fdContent.ContentStart, fdContent.ContentEnd);
            trContent.Load(fsHelpfile, DataFormats.Rtf);
            Hyperlinks.SubscribeToAllHyperlinks(fdContent);
        }
     public FlowDocument Document
        {
        get
            {
            return fdContent;
            }
        set
            {
            fdContent = value;
            }
        }
    private FlowDocument fdContent;
    }

0 个答案:

没有答案