如何判断鼠标是否已被捕获
我创建了一个用户控件,其中包含一个画布和画布上的一个按钮。为了能够在画布上移动按钮,我附加了一个 DragBehavior,如下所示:
class DragOverCanvasBehavior : Behavior<FrameworkElement>
{
private Point _mouseStartPosition;
protected override void OnAttached()
{
AssociatedObject.MouseLeftButtonDown += (sender, e) =>
{
_mouseStartPosition = e.GetPosition((Canvas) AssociatedObject.Parent);
AssociatedObject.CaptureMouse();
};
AssociatedObject.MouseLeftButtonUp += (sender, e) => AssociatedObject.ReleaseMouseCapture();
AssociatedObject.MouseMove += (sender, e) =>
{
var point = e.GetPosition((Canvas)AssociatedObject.Parent) - _mouseStartPosition;
if (AssociatedObject.IsMouseCaptured)
{
Canvas.SetTop(AssociatedObject, point.Y);
Canvas.SetLeft(AssociatedObject, point.X);
}
};
}
}
出于业务原因,如果我按住并拖动画布,我也需要移动画布。我使用类似的Behavior 类来完成此操作,该类更改了Canvas 边距,并使其看起来好像在拖动时随着鼠标指针移动。此行为还捕获鼠标。
现在的问题是 - 如果我单击并拖动按钮,画布也会获取鼠标事件并开始被拖动。如何确保当我拖动按钮时,画布行为不会收到鼠标事件。
我尝试将 e.Handled = true 放入“行为”中,但这不起作用。
如果我发现鼠标已经被其他对象捕获,我可以在行为中添加条件以不再捕获它。
I created a usercontrol which contains a Canvas and a Button on the Canvas. To be able to move the button over the canvas I attached a DragBehavior shown below:
class DragOverCanvasBehavior : Behavior<FrameworkElement>
{
private Point _mouseStartPosition;
protected override void OnAttached()
{
AssociatedObject.MouseLeftButtonDown += (sender, e) =>
{
_mouseStartPosition = e.GetPosition((Canvas) AssociatedObject.Parent);
AssociatedObject.CaptureMouse();
};
AssociatedObject.MouseLeftButtonUp += (sender, e) => AssociatedObject.ReleaseMouseCapture();
AssociatedObject.MouseMove += (sender, e) =>
{
var point = e.GetPosition((Canvas)AssociatedObject.Parent) - _mouseStartPosition;
if (AssociatedObject.IsMouseCaptured)
{
Canvas.SetTop(AssociatedObject, point.Y);
Canvas.SetLeft(AssociatedObject, point.X);
}
};
}
}
For a business reason I need to move the canvas also if I hold and drag the canvas. I did it with a similar Behavior class which changes the Canvas margins and gives it the look as if it's moving along with mouse pointer on drag. This Behavior also captures mouse.
Now the problem is - If I click and drag the Button, the Canvas also gets Mouse events and starts getting dragged. How can I make sure that when I am dragging the Button the Canvas Behavior does not get mouse events.
I tried putting e.Handled = true in Behaviors but that did not work.
If I can find out that the Mouse is already Captured bu some other object, I can put condition in Behavior to not to capture it again.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
测试
Mouse.Captured
!= null
。Test for
Mouse.Captured
!= null
.