2010-08-15 42 views
2

我想以编程方式将WPF超链接元素插入到FlowDocument中。在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中。

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

回答

5

使用它接受的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:

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

编辑:如果您想使用TextRange.Load,请尝试在超范围内包装超链接:

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返回的结果。

+0

谢谢!超链接构造函数的语法比字符串解析好得多。 – dthrasher 2010-08-16 00:01:18

+0

感谢您的超链接构造函数 – Vikram 2014-11-24 13:38:23