2014-01-19 58 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

你可以用同样的方法用于将文本块添加到容器。

相关问题