MouseDown not triggered?

系统 1690 0

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:

MouseDown not triggered?

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

MouseDown not triggered?

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

 

 

MouseDown not triggered?


更多文章、技术交流、商务合作、联系博主

微信扫码或搜索:z360901061

微信扫一扫加我为好友

QQ号联系: 360901061

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描下面二维码支持博主2元、5元、10元、20元等您想捐的金额吧,狠狠点击下面给点支持吧,站长非常感激您!手机微信长按不能支付解决办法:请将微信支付二维码保存到相册,切换到微信,然后点击微信右上角扫一扫功能,选择支付二维码完成支付。

【本文对您有帮助就好】

您的支持是博主写作最大的动力,如果您喜欢我的文章,感觉我的文章对您有帮助,请用微信扫描上面二维码支持博主2元、5元、10元、自定义金额等您想捐的金额吧,站长会非常 感谢您的哦!!!

发表我的评论
最新评论 总共0条评论