我的程序中基本上有一个简单的问题,我只是想确保一切正常。它应该在单击鼠标按钮时添加MouseEventHandler
,然后随着鼠标移动圆圈,直到事件处理程序被删除。我将代码简化为最基本的:
XAML:
<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 Name="grid1" Background="White" MouseLeftButtonUp="grid_MouseUp">
<Ellipse Height="50" HorizontalAlignment="Left" Margin="12,12,0,0" Name="ellipse1" Stroke="{x:Null}" VerticalAlignment="Top" Width="50" Fill="Black" MouseLeftButtonDown="ellipse1_MouseDown" />
</Grid>
</Window>
C#:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private static Point _oldPoint = new Point(), _newPoint = new Point();
private void ellipse1_MouseDown(object sender, MouseButtonEventArgs e)
{
_oldPoint = e.GetPosition(grid1);
grid1.MouseMove += new MouseEventHandler(grid_MouseMove);
}
private void grid_MouseUp(object sender, MouseButtonEventArgs e)
{
grid1.MouseMove -= new MouseEventHandler(grid_MouseMove);
}
private void grid_MouseMove(object sender, MouseEventArgs e)
{
_newPoint = e.GetPosition(grid1);
ellipse1.Margin = new Thickness(ellipse1.Margin.Left - _oldPoint.X + _newPoint.X, ellipse1.Margin.Top - _oldPoint.Y + _newPoint.Y, 0, 0);
_oldPoint = _newPoint;
}
}
现在总的来说,这段代码工作得很好,我认为它非常简洁,因为它在实际按下按钮之前不会检查鼠标的移动。但是,我的问题如下:
我不得不将MouseMove
事件添加到网格而不是圆圈,因为一旦鼠标指针失去圆圈的焦点(通过移动鼠标太快),它就不会再触发 MouseMove 事件了。但究竟为什么会这样呢?在事件开始时,鼠标肯定在圆圈上方,然后它移动了。是的,它离开了圆圈,但那不应该仍然触发事件吗?