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

Sujiz picture Sujiz · Sep 27, 2011 · Viewed 8.8k times · Source

I have a text box contain links .the contents in the text are generated during run time.My problem is that the links inside the text is not clickable,how can make all links inside the text block clickable so that when i tap a link it should open the web browser.In android we can set it by using autolink.Is such option is available in wp7 or in wp7.1 mango?

Answer

Claus Jørgensen picture Claus Jørgensen · Sep 27, 2011

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();
}