Insert a Hyperlink at a specified position in a WP

2019-07-15 11:59发布

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

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).

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

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

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);
        } 
    }

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?

1条回答
ら.Afraid
2楼-- · 2019-07-15 12:26

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/");

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/");

Edit: 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>";

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

查看更多
登录 后发表回答