wpf Button.MouseLeftButtonDown doesnt work at all

2020-08-26 06:41发布

Im trying to learn how MouseLeftButtonDown works but no seccuss until now.

When i click on the button, nothing heppends.

<Window x:Class="WpfApplication1.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>
        <StackPanel Name="sss">
            <Button x:Name="b1" Height="213" MouseLeftButtonDown="sss_MouseDown"/>
        </StackPanel>
    </Grid>
</Window>

Code behind is :

private void sss_MouseDown(object sender, MouseButtonEventArgs e)
        {
            MessageBox.Show("3   ->>>>>" + ((Control)sender).Name);
        }

3条回答
贪生不怕死
2楼-- · 2020-08-26 07:04

From the documentation on this event:

Some control classes might have inherent class handling for mouse button events. The left mouse button down event is the most likely event to have class handling in a control. The class handling often marks the underlying Mouse class event as handled. Once the event is marked handled, other instance handlers that are attached to that element are not ordinarily raised. Any other class or instance handlers that are attached to elements in the bubbling direction towards the root in the UI tree are also not ordinarily raised.

So in short: the button is likely handling this event in order to generate its own MouseDown and MouseClick events. Because the button is marking the event as handled, your own handler isn't being called. Try using one of the more standard events instead.

The page also lists a couple of workarounds, but typically I'd steer clear of these and use the more standard solutions.

查看更多
可以哭但决不认输i
3楼-- · 2020-08-26 07:04

I had the same problem but used the PreviewMouseLeftButtonDown event instead. That worked.

查看更多
SAY GOODBYE
4楼-- · 2020-08-26 07:05

try simple PreviewMouseLeftButtonDown event

查看更多
登录 后发表回答