zoukankan      html  css  js  c++  java
  • MouseDown not triggered?

    In following case:

    <Window x:Class="WpfApplication59.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 >

    <Button HorizontalAlignment="Center" VerticalAlignment="Center" MouseDown="Button_MouseDown">test</Button>

    </Grid>

    </Window>

     

    public partial class MainWindow : Window

    {

    public MainWindow()

    {

    InitializeComponent();

    this.AddHandler(Button.MouseDownEvent, new MouseButtonEventHandler(Test), true);

    }

     

    private void Button_MouseDown(object sender, MouseButtonEventArgs e)

    {

    Console.WriteLine("mousedown from button.");

    }

     

    private void Test(object sender, MouseButtonEventArgs e)

    {

    Console.WriteLine("mousedown from test.");

    }

    }

     

    The Button_MouseDown cannot be triggered, because MouseDown is a "bubbling" event, it means that child control on which the event happens handles it first, and only if it
    declines to handle it, the event is passed on to the parent of that
    control (and so on, until it reaches top). If you want to capture the
    event in a parent before the child sees it, you need to use a
    "tunneling" event - in your case, it would be PreviewMouseDown.

     

    As an alternative approach suggested is adding the line
    AddHandler(FrameworkElement.MouseDownEvent, new
    MouseButtonEventHandler(Test), true);
    to your window's constructor after the call to InitializeComponent (and
    remove "MouseDown="Button_MouseDown" from the XAML).

    Below is the mainwindow:

    Click test button, see how the events were handled from snoop:

    First the preview… event is raised, then mousedown event raised, since the mousedown is already handled by button, so you cannot listen it outside.

     

     

  • 相关阅读:
    关于loose.dtd和xhtml1transitional.dtd等文档类型定义模型中CSS失效的解决办法。
    JSON扫盲帖+JSON类教程
    jQuery中Ajax事件
    JQuery绑定事件 时如何传递参数
    xml include 另外一个xml文件
    ubuntu 两张网卡时网络设置
    Letcode 题:pow(x,n)
    Java编程语言中sleep()和yield()的区别
    JProfiler与eclipse集成
    zz 字符串相关
  • 原文地址:https://www.cnblogs.com/bear831204/p/2119810.html
Copyright © 2011-2022 走看看