简体   繁体   English

在画布上拖放形状

[英]Drag & Drop Shapes on Canvas

I put several shapes (like Ellipse and Rectangle ) on a Canvas .我在Canvas上放置了几种形状(如EllipseRectangle )。 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 mouse 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.自己处理鼠标事件和实现拖放肯定会奏效,但根据您尝试执行的操作,您可能能够利用 Expression Blend 行为。 The Microsoft.Expression.Interactions DLL includes some useful basic behaviors, triggers, and actions to be used in Silverlight and WPF. Microsoft.Expression.Interactions DLL 包括一些在 Silverlight 和 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).有一个 MouseDragElementBehavior 为元素实现了基本的拖放功能,无论您的布局容器如何,它都应该可以工作(因此您不会被限制在 Canvas 中)。 You can drop this behavior onto an element using Blend, or define it directly in XAML if you would like:如果您愿意,可以使用 Blend 将此行为拖放到元素上,或者直接在 XAML 中定义它:

<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.您的项目必须同时引用 System.Windows.Interactivity.dll 和 Microsoft.Expression.Interactions.dll 才能使用此行为。

EDIT (to show attaching this behavior in C# code-behind):编辑(以显示在 C# 代码隐藏中附加此行为):

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.请记住在 using 语句中包含 Microsoft.Expression.Interactivity.Layout 命名空间。

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 HTH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM