在WPF FlowDocument中的指定位置插入超链接 [英] Insert a Hyperlink at a specified position in a WPF FlowDocument

查看:309
本文介绍了在WPF FlowDocument中的指定位置插入超链接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'd like to insert a WPF Hyperlink element into a FlowDocument programmatically.

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

The objective is to create a toolbar button that would take a run of text within a RichTextBox and replace it with a Hyperlink. It's the same sort of interface you see on the web for creating hyperlinks on wikis or in blogs (or on StackOverflow).

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

I can find the TextRange of the selected text like this:

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

我正试图将Hyperlink Xaml填充到TextRange中,如下所示:

And I'm attempting to stuff the Hyperlink Xaml into the TextRange like so:

    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的。

But I still seem to get plain text pasted into the RichTextBox.

我在这里做错了什么?是否有更好的方法来完成我正在尝试做的事情?

What am I doing wrong here? Are there better ways to accomplish what I'm trying to do?

推荐答案

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

Use the constructor for Hyperlink that takes in a TextPointer:

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

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

Or, change the text first and then use the one that takes two TextPointers:

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






编辑:如果你想使用TextRange.Load ,尝试在跨度中包装超链接:


If you want to use TextRange.Load, try wrapping the Hyperlink in a 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返回。

I'm not sure why this works when a plain Hyperlink doesn't, but it's closer to what gets returned by TextRange.Save.

这篇关于在WPF FlowDocument中的指定位置插入超链接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆