Windows WPF 中未触发鼠标事件

Mouse events not firing in Windows WPF

我有一个简单的 WPF 应用程序

<Grid>
    <Border BorderBrush="Black" BorderThickness="1" 
            HorizontalAlignment="Left" Height="388" Margin="10,10,0,0" VerticalAlignment="Top" Width="329"/>
    <Image x:Name="PreviewImg" HorizontalAlignment="Left" Height="400" Margin="10,10,0,0" VerticalAlignment="Top" Width="329"       MouseDown="PreviewImgMouse" AllowDrop="True" PreviewMouseWheel="PreviewImg_PreviewMouseWheel" MouseEnter="Entered"       Focusable="True"></Image>
    <Label Content="Matched Products" HorizontalAlignment="Left" Margin="344,10,0,0" VerticalAlignment="Top" Width="290"/>
    <Label Content="Unknown Products" HorizontalAlignment="Left" Margin="661,10,0,0" VerticalAlignment="Top" Width="290"/>
    <TextBlock x:Name="MatchedProducts" HorizontalAlignment="Left" Margin="349,36,0,0" TextWrapping="Wrap" Text="TextBlock"           VerticalAlignment="Top" Height="362" Width="295"/>
    <TextBlock x:Name="UnknownProducts" HorizontalAlignment="Left" Margin="666,36,0,0" TextWrapping="Wrap" Text="TextBlock"           VerticalAlignment="Top" Height="362" Width="295"/>
    <Grid HorizontalAlignment="Left" Height="50" Margin="10,410,0,0" VerticalAlignment="Top" Width="957">
        <Button x:Name="FinalizeBtn" Content="Finalize" HorizontalAlignment="Left" Margin="826,10,0,0" VerticalAlignment="Top"        Width="120" Height="30"/>
        <Button x:Name="NewEntryBtn" Content="Create new entry" HorizontalAlignment="Left" Margin="701,10,0,0"
                VerticalAlignment="Top" Width="120" Height="30"/>
        <Button x:Name="FreeBtn" Content="Free Button" HorizontalAlignment="Left" Margin="576,10,0,0" VerticalAlignment="Top"        Width="120" Height="30"/>
    </Grid>
</Grid>

图像组件下定义的所有事件都没有触发,我尝试了所有谷歌第一页搜索,但 none 其中有效。

我了解了我的应用程序中路由事件的区别,MouseDownPreviewMouseDown 都应该起作用。

唯一可以遮挡图像的是 Border 组件,但我试过没有它但仍然没有,因为它首先被声明图像应该覆盖它...?

所有函数名称都是正确的,因为它们是自动生成的。

如果有帮助,我可以粘贴到 .cs 文件中。

谢谢

E1:不知何故它现在可以工作了,但我不知道是什么修复了它... 我所做的一项更改是调整边框内的图像:

<Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="388" Margin="10,10,0,0" VerticalAlignment="Top" Width="329">
    <Image x:Name="PreviewImg" Height="400" Margin="0" VerticalAlignment="Center" HorizontalAlignment="Center" Width="329" MouseDown="PreviewImgMouse" AllowDrop="True" PreviewMouseWheel="PreviewImg_PreviewMouseWheel" MouseEnter="Entered" Focusable="True"/>
</Border>

但我无法想象这会修复它。

您需要像 <Image Source="image.jpg" 一样为图像定义来源。没有图像,事件将不会触发。

实现您想要的效果的一种方法是将图像放在按钮中并删除按钮样式。这里有一个很好的例子:

WPF Image Control with Click Event

对于高级用户

  • 使用样式为图像的按钮,请参阅@Richard 的回答 WPF Image Control with Click event 感谢 link。

初学者

  • Image 组件需要一个源来触发@Örvar 发布的事件。添加透明源是解决方案,尽管是一个 hacky 的解决方案。

如果我或其他人找到更好的解决方案,我会更新此答案。 (或者投反对票离开,这也有帮助...)