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"></Butt开发者_如何学编程on>
</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?
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?
If you add the handlers with code like this:
dgv.AddHandler(DataGrid.MouseLeftButtonDownEvent, new MouseButtonEventHandler(dgv_MouseLeftButtonDown), true);
dgv.AddHandler(DataGrid.MouseLeftButtonUpEvent, new MouseButtonEventHandler(dgv_MouseLeftButtonUp), true);
and make sure you pass true in the last argument "HandledEventsToo" I think you will get it to work - I did...
Have you ever noticed that the MouseLeftButtonDown and MouseLeftButtonUp events are not fired when a Silverlight button is clicked? The reason for this is that the button handles these two events itself by overriding the OnMouseLeftButtonDown and the OnMouseLeftButtonUp handlers. In the OnMouseLeftButtonDown override, the Click event is raised and the MouseLeftButtonDown event is marked as handled so it couldn't bubble in the visual tree. The OnMouseLeftButtonUp override also marks the MouseLeftButtonUp as handled.
This thing can be changed using the ClickMode property of the Button control. It has the following values - Hover, Press, Release. The default one is Pressed and we have already explained it. When we have ClickMode set to Release, the Click event will be raised in the OnMouseLeftButtonUp override and the MouseLeftButtonDown and MouseLeftButtonUp events will be handled inside the button again. If we set the ClickMode to Hover, the Click event will be raised with the MouseEnter event and we will also be able to use the mouse button events.
精彩评论