A quick and easy extension to HyperlinkButton for Windows Phone 7

30 November 2010

While doing some application building, I naively assumed that I could just put a web address in the NavigateUri field of the HyperlinkButton control (Windows Phone 7) and have it just magically work.

UPDATED 12/3/2010: I’ve made improvements that you will find here: http://www.jeff.wilcox.name/2010/12/updated-phone-hyperlink-button/ 

Turns out you need to actually handle the Click event yourself and setup the proper task for that, unless you’re doing local within-the-app navigation.

I wrote a super simple PhoneHyperlinkButton control that derives from HyperlinkButton. No custom template or style, so just drop the file into any project and you’re off and running.

Set the “Tag” property of your instance to be the URI or e-mail address you’d like the message to go to: if it starts with mailto:, then it’ll use the EmailComposeTask. Otherwise, the web browser task.

// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Public License (Ms-PL).
// Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
// All other rights reserved.

using System.Diagnostics;
using System.Windows.Controls;
using Microsoft.Phone.Tasks;

namespace Microsoft.Phone.Controls.Unofficial
{
    /// <summary>
    /// An extended HyperlinkButton control that uses the Tag property to
    /// handle web browser or e-mail compose task intended use on the phone.
    /// </summary>
    public class PhoneHyperlinkButton : HyperlinkButton
    {
        protected override void OnClick()
        {
            base.OnClick();

            Debug.Assert(Tag is string, "You need to set the Tag property!");
            string tag = (string)Tag;

            int i = tag.IndexOf("mailto:");
            if (i >= 0)
            {
                tag = tag.Substring(i + 7);
                EmailComposeTask ect = new EmailComposeTask
                {
                    To = tag,
                };
                ect.Show();
            }
            else
            {
                // Assume the web.
                WebBrowserTask wbt = new WebBrowserTask
                {
                    URL = (string)Tag,
                };
                wbt.Show();
            }
        }
    }
}

Hope this helps. Oh, and remember that once the task completes, your app will likely be tombstoned.

Jeff Wilcox is a Software Engineer at Microsoft in the Open Source Programs Office (OSPO), helping Microsoft engineers use, contribute to and release open source at scale.

comments powered by Disqus