如何在代码中的TextBlock中添加超链接?

时间:2014-01-19 07:57:39

标签: c# wpf textblock

this question(来自eandersson的答案)中,在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;
}

1 个答案:

答案 0 :(得分:8)

以下是在中间添加带有可点击链接的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

您可以将addidng文本块用于容器。