Search code examples
c#wpfmouseleftbuttondown

wpf Button.MouseLeftButtonDown doesnt work at all


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);
        }

Solution

  • 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.