【问题标题】:Insert a Hyperlink at a specified position in a WPF FlowDocument在 WPF FlowDocument 中的指定位置插入超链接
【发布时间】:2011-03-29 23:51:27
【问题描述】:

我想以编程方式将 WPF 超链接元素插入 FlowDocument。

目标是创建一个工具栏按钮,该按钮将在 RichTextBox 中获取一系列文本并将其替换为超链接。它与您在网络上看到的用于在 wiki 或博客(或 StackOverflow)上创建超链接的界面相同。

我可以像这样找到所选文本的 TextRange:

    TextRange tr = new TextRange(
    MyRichTextBox.Selection.Start,
    MyRichTextBox.Selection.End);

我正在尝试将超链接 Xaml 填充到 TextRange 中,如下所示:

    string rawXaml = "<Hyperlink xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\" NavigateUri=\"http://www.google.com/\">Google Home Page</Hyperlink>";

    using(MemoryStream stream = new MemoryStream())
    {
        StreamWriter writer = new StreamWriter(stream);
        writer.Write(rawXaml);
        writer.Flush();
        stream.Position = 0;

        if (tr.CanLoad(DataFormats.Xaml))
        {
            tr.Load(stream, DataFormats.Xaml);
        } 
    }

但我似乎仍然将纯文本粘贴到 RichTextBox 中。

我在这里做错了什么?有没有更好的方法来完成我想做的事情?

【问题讨论】:

    标签: wpf insert richtextbox hyperlink flowdocument


    【解决方案1】:

    使用接受 TextPointer 的 Hyperlink 构造函数:

    tr.Text = "";
    Run run = new Run("Google Home Page");
    Hyperlink hlink = new Hyperlink(run, tr.Start);
    hlink.NavigateUri = new Uri("http://www.google.com/");
    

    或者,先更改文本,然后使用带有两个 TextPointer 的文本:

    tr.Text = "Google Home Page";
    Hyperlink hlink = new Hyperlink(tr.Start, tr.End);
    hlink.NavigateUri = new Uri("http://www.google.com/");
    

    编辑:如果您想使用 TextRange.Load,请尝试将超链接包装在 Span 中:

    string rawXaml = "<Span xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"><Hyperlink NavigateUri=\"http://www.google.com/\">Google Home Page</Hyperlink></Span>";
    

    我不确定为什么当普通超链接不起作用时这会起作用,但它更接近 TextRange.Save 返回的内容。

    【讨论】:

    • 谢谢!无论如何,超链接构造函数语法比字符串解析要好得多。
    • 感谢超链接构造函数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-17
    • 1970-01-01
    • 1970-01-01
    • 2010-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多