2014-01-19 59 views
1

this question(來自eandersson的回答)中,超鏈接用在TextBlock內。我想要做同樣的事情,但在代碼背後 - 如何做到這一點?從鏈接如何在代碼中的TextBlock中添加超鏈接?

例子:

<TextBlock>   
    <Hyperlink NavigateUri="http://www.google.com" RequestNavigate="Hyperlink_RequestNavigate"> 
     Click here 
    </Hyperlink> 
</TextBlock> 

private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e) 
{ 
    Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri)); 
    e.Handled = true; 
} 

回答

6

下面的代碼添加一個TextBlock在中間一個可點擊的鏈接:

Run run1 = new Run("click "); 
Run run2 = new Run(" Please"); 
Run run3 = new Run("here."); 

Hyperlink hyperlink = new Hyperlink(run3) 
         { 
          NavigateUri = new Uri("http://stackoverflow.com") 
         }; 
hyperlink.RequestNavigate += new System.Windows.Navigation.RequestNavigateEventHandler(hyperlink_RequestNavigate); //to be implemented 
textBlock1.Inlines.Clear(); 
textBlock1.Inlines.Add(run1); 
textBlock1.Inlines.Add(hyperlink); 
textBlock1.Inlines.Add(run2); 

programmatically make textblock with hyperlink in between text

你可以用同樣的方法用於將文本塊添加到容器。

相關問題