Why don’t I get MouseUp events in the Bing Maps Silverlight Component

The Bing Maps Silverlight component (currently in CTP) allows you to overlay items on the map, but it does some odd things to mouse events. Take the following Xaml:


<UserControl x:Class="BingBlogPost.MainPage"
 xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
 xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
 xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
 xmlns:map="clr-namespace:Microsoft.VirtualEarth.MapControl;assembly=Microsoft.VirtualEarth.MapControl"
 mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
 <Grid x:Name="LayoutRoot">
 <map:Map>
 <Border Padding="8"
 Background="Gray"
 HorizontalAlignment="Center"
 VerticalAlignment="Center"
 MouseLeftButtonUp="Message_Click"
 >
 <TextBlock Text="Click here"/>
 </Border>
 </map:Map>
 </Grid>
</UserControl>

This will show the world map, with our ‘control’ in the centre. Now, mouse handling is interesting using the map component. You’ll notice that if you click and drag on the control, the map underneath will drag. In this example we’ve got an event handler which is set to receive the button up event (to simulate a mouse click). here’s the event handling code:

private void Message_Click(object sender, MouseButtonEventArgs e)
{
     MessageBox.Show(“Clicked!”);
}

But you’ll notice that this event doesn’t fire on a single click. Oddly, it does fire after a double-click. So clearly, the map itself is doing something tricky with events.

If you want to get a click event, there’s two things you can do. You could put in an actual button. This handles mouse events properly and will pass on its own Click event as you’d expect. But if you want to roll your own, there’s a simple trick: add a handler on the control for MouseLeftButtonDown and handle it with this code:

private void Message_MouseDown(object sender, MouseButtonEventArgs e)
{
     e.Handled = true;
}

This is enough to stop the map eating the mouse down event and capturing the mouse (which is why you never get the event). You’ll get the Up event as you expect and you can handle it normally.

Advertisements

One comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s