Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mousedown event firing twice (WPF)

I am currently trying to capture a mousedown from an image on a simple grid. I have no problems with the event firing, it is just that it fires twice. And because clicking it twice will eventually have a different state (it will show an expanded image), going straight to second click is causing problems.

My current code is as follows:

XAML

<Window x:Class="WpfApplication.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid Background="Transparent" x:Name="MainContent" MouseDown="Generic_MouseDown">
        <Image Source="http://www.blogcdn.com/www.engadget.com/media/2011/05/welcome-kansas-city-google-high-speed-internet.jpg" Height="100" Width="100" MouseDown="Generic_MouseDown"/>
    </Grid>
</Window>

Code:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    private void Generic_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if (((FrameworkElement)e.Source).GetType() == typeof(System.Windows.Controls.Image))
        {
            Console.Out.WriteLine("image clicked");
        }
        else
        {
            Console.Out.WriteLine("grid clicked");
        }

    }
}

So when I click the image, it fires mousedown twice.

Thanks!

like image 294
Angelus Avatar asked May 17 '11 17:05

Angelus


2 Answers

private void Generic_MouseDown(object sender, MouseButtonEventArgs e)
{
    if (((FrameworkElement)e.Source).GetType()   
           == typeof(System.Windows.Controls.Image))
    {
        Debug.WriteLine("image clicked");
        e.Handled = true;
    }
    else
    {
        Debug.WriteLine("grid clicked");
    }

}

You need to set the Handled property to true.

like image 133
Mike Diaz Avatar answered Oct 29 '22 16:10

Mike Diaz


You would need to set e.Handled to true to prevent the event from bubbling up from the Image to the Grid.

Effectively, what is happening is the event is raised on the Image, then if it's not handled it is raised on the Grid, and so on up the visual tree.

like image 22
CodeNaked Avatar answered Oct 29 '22 16:10

CodeNaked