views:

712

answers:

1

For the life of me, I can not get this to work. I can get MouseEnter, MouseLeave, and Click events to fire, but not MouseLeftButtonDown or MouseLeftButtonUp.

Here's my XAML

    <UserControl x:Class="Dive.Map.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" >
        <Canvas x:Name="LayoutRoot" MouseLeftButtonDown="LayoutRoot_MouseLeftButtonDown">
            <Button x:Name="btnTest" Content="asdf" Background="Transparent"  MouseLeftButtonDown="btnTest_MouseLeftButtonDown"></Button>
        </Canvas>
    </UserControl>

And here's my code

public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();
    }

    private void btnTest_MouseLeftButtonDown( object sender, MouseButtonEventArgs e )
    {
        btnTest.Content = DateTime.Now.ToString();
    }

    private void LayoutRoot_MouseLeftButtonDown( object sender, MouseButtonEventArgs e )
    {
        e.Handled = false;
    }
}

What am I doing wrong?

+1  A: 

The Button control (or more specifically the ButtonBase super-class from which it derives) handles the MouseLeftButtonDown event itself in order to generate the Click event. Hence you cannot get a MouseLeftButtonDown event from the standard Button.

Is there a reason you aren't using the Click event?

AnthonyWJones
I have a button that acts as a drag and drop handle. I wanted to detect when a user pushed down on the button so then I could start repositioning my control during the MouseMove, and then stop repositioning on the MouseUp event. What should I do instead?
Matt
@Matt: Stop using a button for a drag and drop handle? It really depends on __why__ you want this. For example if you are creating some kind of UI builder then you would place the button in a Grid which also has a transparent canvas covering the button. Then you can manage the events on the canvas. Note the Canvas and the button would be siblings, the button would not be a child of the Canvas.
AnthonyWJones
Cool. I ended up creating a content template for my button and then listened for the MouseDown/MouseUp events on the ControlTemplate elements.
Matt