2 minute read

This is an implementation of a container that can be moved, dragged within the scope of a Silverlight Application.  Currently, the FloatingContainer is derived from ItemsControl.  Feel free to derive it from any Silverlight Control - the code though remains the same.

Note: Floating behavior is functional only when the control is placed on the canvas.

[sourcecode language='csharp']

public class FloatingContainer : ItemsControl
    {

        // Global variable to indicate if user has clicked and started/stopped moving.
        private bool moving = false;

        // position - X
        private double offSetX;

        // position - Y
        private double offSetY;

        protected override void OnMouseLeftButtonDown(MouseButtonEventArgs e)
        {
            // Left mouse button clicked within boundary of the container, so start moving.
            moving = true;
            Point offset = e.GetPosition(this);
            offSetX = offset.X;
            offSetY = offset.Y;
            base.OnMouseLeftButtonDown(e);
        }

        protected override void OnMouseLeftButtonUp(MouseButtonEventArgs e)
        {

            // Left mouse button is released, so stop moving.
            moving = false;
            base.OnMouseLeftButtonUp(e);
        }
        protected override void OnMouseMove(MouseEventArgs e)
        {

            if (moving)
            {

                // Get the new mouse pointer position
                Canvas parent = (Canvas)this.Parent;
                Point p = e.GetPosition(parent);
                double x = p.X - offSetX;
                double y = p.Y - offSetY;

                // Set the new position for the control.
                this.SetValue(Canvas.LeftProperty, x);
                this.SetValue(Canvas.TopProperty, y);
            }
            base.OnMouseMove(e);
        }

    }

[/sourcecode]