After recently searching for a way to do this and finding nothing I thought I would share a solution. It involves using the ever useful AddHandler method on the UIElement you wish to detect the mouse down on and simply setting a flag. Job done.
It is worth noting that popups and child windows may appear on top of the UIElement which the handler is attached to.
Code Snippet:
this.AddHandler(UIElement.MouseLeftButtonDownEvent, new MouseButtonEventHandler(MainPageMouseLeftButtonDown), true); this.AddHandler(UIElement.MouseLeftButtonUpEvent, new MouseButtonEventHandler(MainPageMouseLeftButtonUp), true); void MainPageMouseLeftButtonUp(object sender, MouseButtonEventArgs e) { MouseDown = false; } void MainPageMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { MouseDown = true; }
Bug: MouseDown equals True incorrectly.
Reproducing the bug: Press the left mouse button inside the silverlight control, move the mouse outside the silverlight control and release the press. Continue to move the mouse, without doing any clicking, into the silverlight control. You should now see that it still displays “MouseDown: True”, which is incorrect since the mouse button was released. I’m just joking with you…this only the fault of silverlight developers at microsoft. Luckily they’re either canned or reassigned at this moment. Shitty programmers… Not even SL5 is complete.
@Programmer
Hi sorry for slow reply and thanks for contributing.
Yeah there is not much we can do about that as moving out of the applet makes it a bit hard for them to detect the mouse up. But I think shitty programmers may be a little harsh 😛
There is a quick hacky workaround, in that you could detect when the mouse leaves the applet and set the mousedown flag accordingly.
Cheers,
J