首页 > 解决方案 > 鼠标事件未在 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>

Image 组件下定义的所有事件都没有触发,我尝试了所有谷歌的首页搜索,但它们都不起作用。

我在我的应用程序中读到了路由事件的区别MouseDown并且PreviewMouseDown应该可以工作。

唯一可以阻止图像的是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>

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

标签: c#wpfeventswpf-controlsmouseevent

解决方案


对于高级用户

给菜鸟的

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

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


推荐阅读