Google Search

Monday, April 6, 2009

Creating customizable WPF drop-down menus (2)


Step 2: Detecting drag


Drag will start when the user had pressed the mouse button on an item and moved it enough distance in pixels while being pressed.
So, we need to know where the mouse was pressed, then track it all time it is pressed until it moves far enough:
public class DraggableMenuItem : MenuItem
{
    private Point m_dragStartPoint;

    public static  bool IsDragging { get; set; }

    protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
    {
        m_dragStartPoint = e.GetPosition(this);
        base.OnMouseLeftButtonDown(e);
    }

    protected override void OnMouseMove(MouseEventArgs e)
    {
        if (e.LeftButton != MouseButtonState.Pressed || IsDragging)
            return;

        Point p = e.GetPosition(this);
        if (Point.Subtract(m_dragStartPoint, p).LengthSquared < 16)
        {
            e.Handled = true;
            return;
        }

        DoDragging();
    }

    protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
    {
        IsDragging = false;
        base.OnMouseLeftButtonUp(e);
    }

    private void DoDragging()
    {
    }
}
Note that the IsDragging flag is a static flag, thus shared among all instances of the DraggableMenuItem. In the code sample above we do not yet assign it. This will be done in the next steps, in addition to some other places we will need to use its value to achieve the correct behavior.

No comments:

Post a Comment