Insert a Hyperlink at a specified position in a WPF FlowDocument

*爱你&永不变心* 提交于 2019-12-24 00:37:39

问题


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:


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.



来源:https://stackoverflow.com/questions/3485937/insert-a-hyperlink-at-a-specified-position-in-a-wpf-flowdocument

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!