以编程方式在文本块中添加超链接按钮

时间:2016-03-29 10:25:24

标签: c# xaml windows-phone-8 hyperlink

如何通过文本末尾的c#在文本块中添加超链接按钮。 在XAML部分,我有一个文本块

<TextBlock  Name="PresenterDescription" TextWrapping="Wrap"  Foreground="White" MinHeight="200" FontSize="16"/>

在.cs文件中我这样做..

Run run1 = new Run();
run1.Text = "some text";
HyperlinkButton hyperlinkButton = new HyperlinkButton()
{
    Content = " read more..",
    HorizontalAlignment = HorizontalAlignment.Left,
    NavigateUri = new Uri("http://somelink.com", UriKind.Absolute)
};
PresenterDescription.Inlines.Add(run1);

但是如何将超链接按钮添加到此文本块?,因为我无法将其添加为内联..

2 个答案:

答案 0 :(得分:1)

无法添加HyperlinkBut​​ton而是可以将HyperLink添加到TextBlock,或者您可以像这样使用RichTextBlock

     <RichTextBlock x:Name="textblock"/>

 Run run1 = new Run();
run1.Text = "some text";
HyperlinkButton hyperlinkButton = new HyperlinkButton()
{
    Content = " read more..",
    HorizontalAlignment = HorizontalAlignment.Left,
    NavigateUri = new Uri("http://somelink.com", UriKind.Absolute)
};
Paragraph para = new Paragraph();
InlineUIContainer inline = new InlineUIContainer();
inline.Child = hyperlinkButton;
para.Inlines.Add(run1);
para.Inlines.Add(inline);
textblock.Blocks.Add(para);

答案 1 :(得分:0)

XAML部分,我做了以下

<RichTextBox  Name="PresenterDescription"  VerticalAlignment="Top" FontSize="16">
            <Paragraph >
                       <Hyperlink Click="readMoreclick">
                            <Underline Foreground="White">read more..</Underline>
                      </Hyperlink>
             </Paragraph>
 </RichTextBox>

c#部分中,要在链接之前显示的文本为..

PresenterDescription.Selection.Text = "Text to be displayed";

最后是链接点击的事件处理程序..

  private void readMoreclick(object sender, RoutedEventArgs e)
         {
            WebBrowserTask webBrowserTask = new WebBrowserTask();
            webBrowserTask.Uri = new Uri("www.example.com", UriKind.Absolute);
            webBrowserTask.Show();
         }