How to set the links in a text block clickable in wp7

左心房为你撑大大i 提交于 2019-11-30 07:29:57

Use a HyperLink.

<TextBlock>
    <Run>Pure Text</Run>
    <Hyperlink Command="{Binding HyperLinkTapped}">http://google.com</Hyperlink>
    <Run>Pure Text Again</Run>
</TextBlock>

This is supported from Windows Phone 7.1 (Mango).

You can create your own FlowDocument from the your data, at runtime, if necessary.

Example on how to generate a FlowDocument from a string:

private void OnMessageReceived(string message)
{
    var textBlock = new RichTextBox()
    {
        TextWrapping = TextWrapping.Wrap,
        IsReadOnly = true,
    };

    var paragraph = new Paragraph();

    var runs = new List<Inline>();

    foreach (var word in message.Split(' '))
    {
        Uri uri;

        if (Uri.TryCreate(word, UriKind.Absolute, out uri) ||
           (word.StartsWith("www.") && Uri.TryCreate("http://" + word, UriKind.Absolute, out uri)))
        {
            var link = new Hyperlink();
            link.Inlines.Add(new Run() { Text = word });
            link.Click += (sender, e) =>
            {
                var hyperLink = (sender as Hyperlink);
                new WebBrowserTask() { Uri = uri }.Show();
            };

            runs.Add(link);
        }
        else
        {
            runs.Add(new Run() { Text = word });
        }

        runs.Add(new Run() { Text = " "});
    }

    foreach (var run in runs)
        paragraph.Inlines.Add(run);

    textBlock.Blocks.Add(paragraph);

    MessagesListBox.Children.Add(textBlock);
    MessagesListBox.UpdateLayout();
}

There is no built in functionality to do this.

If your text (including the links) is HTML you could display it in a WebBrowser control.
If not you'll need to parse the text and build the links yourself. (A combination of TextBlocks and HyperlinkButtons inside a WrapPanel is probably the way to go for this.)

Oleg Koposov

In silverlight RichTextBox contol can help you.

<RichTextBox>
    <Paragraph>
        <Run Text="This have to navigate me to Google: "/>
        <Hyperlink NavigateUri="http://google.com" TargetName="_blank">google.com</Hyperlink>
    </Paragraph>
</RichTextBox>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!