Skip to content

Instantly share code, notes, and snippets.

@fiveisprime
Created June 17, 2012 01:42
Show Gist options
  • Save fiveisprime/2943110 to your computer and use it in GitHub Desktop.
Save fiveisprime/2943110 to your computer and use it in GitHub Desktop.
MouseDragElement behavior with code behind
Canvas designArea = (Canvas)sender;
// Create the rectangle and give it a border and fill.
// Note that a rectangle with no fill requires users to drag from the border only.
Rectangle rectangle = new Rectangle();
rectangle.Height = 120;
rectangle.Width = 90;
rectangle.StrokeThickness = 1;
rectangle.Stroke = new SolidColorBrush(Colors.Black);
rectangle.Fill = new SolidColorBrush(Colors.White);
// Add the MouseDragElementBehavior to the rectangle.
// This rectangle needs to only be moveable within the design area
// so use the ConstrainToParentBounds flag.
Interaction.GetBehaviors(rectangle).Add(
new MouseDragElementBehavior()
{
ConstrainToParentBounds = true
});
// Get the position of mouse within the parent. This serves as a
// reference point for placing the rectangle.
Point position = e.GetPosition(designArea);
// Set the attached properties for the rectangles position
// relative to the design area.
rectangle.SetValue(
Canvas.TopProperty,
position.Y - (rectangle.Height / 2));
rectangle.SetValue(
Canvas.LeftProperty,
position.X - (rectangle.Width / 2));
// Now add the new rectangle to the design area canvas.
designArea.Children.Add(rectangle);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment