我正在实施一个简单的Drag'n'Drop Bahevior。 首先,我订阅鼠标事件:
protected override void OnAttached()
{
base.OnAttached();
base.AssociatedObject.PreviewMouseLeftButtonDown += this.AssociatedObject_PreviewMouseLeftButtonDown;
base.AssociatedObject.PreviewMouseLeftButtonUp += this.AssociatedObject_PreviewMouseLeftButtonUp;
base.AssociatedObject.PreviewMouseMove += this.AssociatedObject_PreviewMouseMove;
}
然后我抓住了鼠标:
private void AssociatedObject_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.startPoint = e.GetPosition(base.AssociatedObject);
base.AssociatedObject.CaptureMouse();
}
处理鼠标移动:
private void AssociatedObject_PreviewMouseMove(object sender, MouseEventArgs e)
{
if (base.AssociatedObject.IsMouseCaptured)
{
...
}
}
在按下鼠标按钮后立即输入此方法时,IsMouseCaptured为true。但是在IsMouseCaptured之后输入它总是假的。我做错了什么?
提前致谢!
答案 0 :(得分:2)
感谢Hans Passant,我已经像这样更新了代码:
/// <summary>
/// Handles pressing Mouse Button over the Control.
/// </summary>
private void AssociatedObject_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
this.startPoint = e.GetPosition(base.AssociatedObject);
base.AssociatedObject.CaptureMouse();
e.Handled = true;
}
将事件标记为已处理有助于在拖动时捕获鼠标。