Raj
Raj

Reputation: 636

Silverlight event MouseLeftButtonDown not fired

I ran into the problem where in Silverlight event MouseLeftButtonDown is not being fired for Button and hyperlinkButton. Looks like it is handled somewhere in the framework. How I can override this behavior

In the XAML code below When I click on the button Named Cancel, Button_MouseLeftButtonDown is not fired. I tried putting textblock within the button , MouseLeftButtonDown works when I click on the text on the button, but it is not bubbled up to the Frame

    <Button Name="Cancel" ClickMode="Release" MouseLeftButtonDown="Button_MouseLeftButtonDown">
            <Button.Content>
                <TextBlock Name="CancelInnerText" MouseLeftButtonDown="TextBlock_MouseLeftButtonDown">Clone Page</TextBlock>
            </Button.Content>

Upvotes: 3

Views: 6803

Answers (4)

Abhishek Gahlout
Abhishek Gahlout

Reputation: 3462

you can call AddHandler method for MouseLeftButtonDown event (as following) and the event will get fired in your code.

button1.AddHandler(Button.MouseLeftButtonDownEvent, new  ouseButtonEventHandler(button1_MouseLeftButtonDown), true);

private void button1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
        // your code
}

Upvotes: 0

Daniel Greitens
Daniel Greitens

Reputation: 1

You are not serious! What happens if a user touches a cancel button on a large form? Just firing what is connected to the cancel button??

The magic has to do with focus-mechanism, coming from control. It will redirect all events to the focused element (in a static class deep in the framework). And on mousebuttondown, this focus is set via base.Focus();

So: Just override MouseLeftButtonDown and set the focus and everything works fine.

Example of a control that can be placed within a button (or a button template):

public class InAction : ContentControl
{
    public InAction()
    {
        this.DefaultStyleKey = typeof(InAction);
        this.MouseLeftButtonDown += new MouseButtonEventHandler(InAction_MouseLeftButtonDown);
    }

    void InAction_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        base.Focus();   
    }
}

Upvotes: 0

James Hollister
James Hollister

Reputation: 537

Yeah, I'm not sure what you're going for here. Is this some type of odd situation or are you just looking to have a button that fires an event when you're clicking it?

If its just a normal button you would typically use the default behavior of:

    <Button Name="Cancel" Click="Button_Click">
        <Button.Content>
            <TextBlock>Clone Page</TextBlock>
        </Button.Content>
    </Button>

Upvotes: 0

Raj
Raj

Reputation: 636

Got it to work, had to set the ClickMode="Hover" for the button. Now MouseLeftButtonDown event is firing and also bubbling

Upvotes: 7

Related Questions