MouseDown event of image in usercontrol not fireing

1.4k views Asked by At

I made a usercontrol in WPF with an image in it. I declared a MouseDown event for this image:

<Image x:Name="imgState" Height="300" Width="300" MouseDown="imgState_MouseDown" OpacityMask="#00000000" />

I placed this usercontrol on my application form, but the event isn't fireing. I'm pretty new to WPF and I read about RoutedEvents but I don't really understand it. I would be happy if someone could help and explain this to me!

Update

Changing to PreviewMouseDown didn't fire the event too. I tried setting the background to transparent and even tried with a blank 300x300 image. The grid workaround doesn't fire the event too. Here is how my code behind looks like:

private void imgState_MouseDown(object sender, MouseButtonEventArgs e)
{
//Some code here
}

Update 2

Here is my whole XAML file:

<UserControl x:Class="TicTacToe.controls.SingleField"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>
        <Image x:Name="imgState" MouseDown="imgState_MouseDown"  Height="300" Width="300" Stretch="None" OpacityMask="#00000000"/>

    </Grid>
</UserControl>

I removed the source again because I set one from code behind at runtime and adding a transparent/clear image didn't helped.

3

There are 3 answers

0
Kimmax On BEST ANSWER

Okay I solved the problem myself.

The problem was the setting OpacityMask="#00000000" that prevented the image from appearing so there were, as @lll said, nothing to hit. I don't know when the setting was set, but I think it happened automatically while expanding the Representation tab.

Thanks for helping me!

6
123 456 789 0 On

You probably want PreviewMouseUp instead of MouseDown event

<Image x:Name="imgState" Height="300" Width="300" 
 PreviewMouseUp="ImgState_OnPreviewMouseUp" 
 PreviewMouseDown="ImgState_OnPreviewMouseDown"/>

Either of the two, you can capture the event from there.

0
florianbaer On

If the answer above does not help:

Not a very nice solution but does work so many times:

Wrap your image with a grid on which you will have your event...

<Grid MouseDown="imgState_MouseDown">
<Image/>
</Grid>