Constraining the Mouse to a Graphical Element
I was creating a dashboard application which I needed to give the ability to drag and move a widget around a tab control item. The user is able to do this on the fly so I needed to do all the code in the code behind dynamically. I set up the code to handle the mouse down, move, and up first (This code will most likely make it in a future blog post, but wanted to keep focused for now). I then added a reference to the Microsoft Expressions and added the following line to my using statements.
using Microsoft.Expression.Interactivity.Layout;
Add the following to the widget creation.
//...Code to handle widget creation MouseDragElementBehavior mouseBehavior = new MouseDragElementBehavior(); mouseBehavior.ConstrainToParentBounds = true; //Here you can attach whichever dependency object you need, //my widget is a chart, thus why I have chart there mouseBehavior.Attach(chart); //..more code to handle widget creation
This will work even if the horizontal and vertical alignment is equal to stretch.
I hope this helps… Happy Coding!