Drag & Drop Shapes on Canvas
I put several shapes (like Ellipse
and Rectangle
) on a Canvas
.
Now, I want user to be able to drag & drop these shapes.
Is there some predefined functionality that I can use, or I should implement the drag & drop myself using the mous开发者_StackOverflowe events ?
Thanks !
Handling the mouse events and implementing drag and drop yourself will certainly work, but depending on what you are trying to do you may be able to leverage Expression Blend behaviors. The Microsoft.Expression.Interactions DLL includes some useful basic behaviors, triggers, and actions to be used in Silverlight and WPF.
There is a MouseDragElementBehavior that implements a basic drag and drop functionality for an element, which should work regardless of your layout container (so you wouldn't be constrained to a Canvas). You can drop this behavior onto an element using Blend, or define it directly in XAML if you would like:
<Rectangle Fill="Red" Stroke="Black" HorizontalAlignment="Left" Width="100" Height="100">
<i:Interaction.Behaviors>
<il:MouseDragElementBehavior/>
</i:Interaction.Behaviors>
</Rectangle>
Your project will have to reference both System.Windows.Interactivity.dll and Microsoft.Expression.Interactions.dll to use this behavior.
EDIT (to show attaching this behavior in C# code-behind):
Rectangle rect = new Rectangle();
rect.Fill = new SolidColorBrush(Colors.Red);
rect.Width = 100;
rect.Height = 100;
MouseDragElementBehavior dragBehavior = new MouseDragElementBehavior();
dragBehavior.Attach(rect);
Remember to include the Microsoft.Expression.Interactivity.Layout namespace with your using statements.
I believe you will need to do this yourself, using the mouse events and the visual tree. Here is an article I believe will help - link text. If not I have some sample code that I can post later this evening.
HTH
精彩评论