2012年3月15日 星期四

Removing the 'Invalid Credentials... ' message from Bing Maps on WP7


How to remove the overlay message you can get when using the Bing Maps control on WP7. Now I've only ever seen this appear for two scenarios - invalid credentials or when in flight mode. It just so happens the control uses the same set of controls to display these messages, example shown below:


Now obviously they don't want you to hide\remove this message :)

The obvious way to remove the 'Invalid credentials...' message is to actual supply valid credentials, but what about if you want to remove the 'Unable to contact server.Please try again' when using the map control in flight mode.

Matt found a previous post that had done this, not sure how this guy was achieving this as the current build for the map control is sealed and access to the RootLayer property is not allowed...

This didn't stop me :) 

So XAML is all about composition - everything is built as layers of UI controls, known as the 'visual tree'. This means you can use extension methods to re-curse the visual tree. I used Colin Eberhardt's linq-to-visual-tree extension methods, available here (LinqToVisualTree.cs).

Here you go...
public partial class MainPage : PhoneApplicationPage
{
    bool removed;
        
    public MainPage()
    {
        InitializeComponent();

        map.ZoomLevel = 8;
        map.Center = new GeoCoordinate(49.109838, -5.976562);
        map.LayoutUpdated += (sender, args) =>
        {
            if (!removed)
            {
                RemoveOverlayTextBlock();
            }
        };
    }

    private void RemoveOverlayTextBlock()
    {
        var textBlock = map.DescendantsAndSelf()
                           .OfType<TextBlock>()
                           .SingleOrDefault(d => d.Text.Contains("Invalid Credentials") ||
                                                 d.Text.Contains("Unable to contact Server"));

        if (textBlock != null)
        {
            var parentBorder = textBlock.Parent as Border;
            if (parentBorder != null)
            {
                parentBorder.Visibility = Visibility.Collapsed;
            }

            removed = true;
        }
    }
}

And you get the following:

沒有留言:

張貼留言