【问题标题】:MouseLeftButtonUp does not fireMouseLeftButtonUp 不触发
【发布时间】:2012-09-11 20:28:44
【问题描述】:

我有一个Button

<Button>
    <Button.Template>
        <ControlTemplate>
            <StackPanel>
                <Image Source="share.png" 
                       MouseLeftButtonUp="Image_MouseLeftButtonUp"
                       MouseLeftButtonDown="Image_MouseLeftButtonDown" />
            </StackPanel>
        </ControlTemplate>
    </Button.Template>
</Button>

但问题是,与 MouseLeftButtonDown 不同,事件 MouseLeftButtonUp 不会触发。为什么?我该如何解决?谢谢。

【问题讨论】:

    标签: c# wpf events button mouseevent


    【解决方案1】:

    正如 Cyborgx37 所说,Click 事件正在处理 LeftMouseUp 事件。

    您可以在按钮上使用PreviewMouseLeftButtonUp 事件而不是MouseLeftButtonUp,如下所示:

    <Button PreviewMouseLeftButtonUp="Button_PreviewMouseLeftButtonUp">
        <Button.Template>
            <ControlTemplate>
                <StackPanel>
                    <Image Source="..." />
                </StackPanel>
            </ControlTemplate>
        </Button.Template>
    </Button>
    

    你的Button模板只有一个Image,我猜你不需要这个Button,你可以像上面那样使用,这样你就可以捕获MouseLeftUp事件了。

    <Image MouseLeftButtonUp="Image_MouseLeftButtonUp" Source="..." />
    

    这种方式要容易得多,但这取决于您的需要。

    顺便说一句,对不起,我的废话英语,我希望它可以帮助你。

    【讨论】:

      【解决方案2】:

      可能是因为 Button 已经在处理该事件,所以它不会过滤到 Image 控件。

      您为什么要处理 Image 上的 MoustUp 和 MouseDown 事件?为什么不在Button 上处理它们?

      编辑
      快速查看此事件的文档后,我发现MouseLeftButtonUp 的路由策略是Direct,但实际的底层事件是MouseUp 事件,它具有Bubbling 策略。因此,实际上,MouseLeftButtonUp 应该有一个事实上的冒泡策略,这意味着Image 应该有机会在Button 之前处理事件。

      听起来可能有其他事情发生。如果您在 Image 控件上将 Image 设置为空,并且背景为 null(不同于 Color.Transparent),则 WPF 会将控件视为不“存在”,就鼠标事件而言。

      编辑 2
      嗯……也许我最初的猜测是正确的。根据这个线程:
      http://social.msdn.microsoft.com/forums/en/wpf/thread/e231919d-9fef-4aa5-9dcb-2c1eb68df25b/#306db880-ed50-45d2-819f-88d76f7148c1
      Button 正在处理MouseUp 事件。尝试使用PreviewMouseUp,然后查看点击了哪个按钮。

      编辑 3
      好的...我想我想通了。我打赌 Button 在 MouseDown 事件中“捕获”了鼠标。发生这种情况时,在释放鼠标之前,其他控件将不会接收 MouseUp 或 MouseDown 事件(包括预览版)。
      见:http://books.google.com/books?id=nYl7J7z3KssC&pg=PA146#v=twopage&q&f=true

      【讨论】:

      • 我必须使用这些事件更改图像源。即使使用 Button 事件 MouseLeftButtonUp 它也不起作用。
      • 我相信MouseLeftButtonUp事件只会在MouseUp之后被调用。由于Button 可能为MouseUpIsHandled 属性设置为true,因此MouseLeftButtonUp 可能永远不会被提升。尝试在Button 上处理MouseUp。 (您甚至可能需要处理 PreviewMouseUp - 不确定事件的处理顺序。)
      【解决方案3】:

      尝试使用事件 PreviewMouseLeftButtonUp。

      【讨论】:

        猜你喜欢
        • 2010-09-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多