2010-08-15 90 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