简体   繁体   English

将元素拖放到画布上

[英]Drag and drop Elements on a Canvas

This may be a very basic question. 这可能是一个非常基本的问题。 I have a canvas, which I put different Elements on in runtime (TextBoxes, Shapes, Buttons). 我有一个画布,在运行时我将其放置在不同的元素上(TextBoxes,Shapes,Buttons)。 Now I want to be able to drag and drop those elements to another location on the same canvas. 现在,我希望能够将这些元素拖放到同一画布上的另一个位置。

Can anyone provide me with some code, how to implement something like onDrag in runtime? 谁能为我提供一些代码,如何在运行时实现类似onDrag的代码?

You can use for example the MouseDown, MouseMove and MouseUp events and then the MouseEventArgs's GetPosition(element) that returns you the coordinates relative to element (there are more events that expose this method). 例如,您可以使用MouseDown,MouseMove和MouseUp事件,然后使用MouseEventArgs的GetPosition(element)返回您相对于元素的坐标(还有更多事件公开此方法)。

Also, take advantage of the RoutedEvent's OriginalSource to check which element inside the canvas was clicked (in this case it's only the rectangle). 另外,利用RoutedEvent的OriginalSource来检查单击画布内的哪个元素(在这种情况下,它只是矩形)。

Here's an example: 这是一个例子:

<Grid>
    <Canvas Name="MyCanvas" PreviewMouseLeftButtonDown="OnMouseDown" MouseMove="OnMouseMove">
        <Rectangle Width="20" Height="20" Canvas.Left="10" Canvas.Top="10" Fill="Blue"/>
        <Rectangle Width="20" Height="20" Canvas.Left="50" Canvas.Top="10" Fill="Red"/>
    </Canvas>
</Grid>

Code-behind: 后台代码:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        AddHandler(Mouse.MouseUpEvent, new MouseButtonEventHandler(OnMouseUp), true);

    }

    private bool _isBeingDragged;

    public void OnMouseDown(object sender, MouseEventArgs args)
    {
        if (!(args.OriginalSource is Canvas))
        {
            _isBeingDragged = true;
        }
    }

    public void OnMouseMove(object sender, MouseEventArgs args)
    {
        if (_isBeingDragged)
        {
            var elementBeingDragged = (FrameworkElement) args.OriginalSource;
            var position = args.GetPosition(MyCanvas);
            Canvas.SetLeft(elementBeingDragged, position.X - elementBeingDragged.ActualWidth / 2);
            Canvas.SetTop(elementBeingDragged, position.Y - elementBeingDragged.ActualHeight / 2);                
        }
    }

    public void OnMouseUp(object sender, MouseEventArgs args)
    {
        _isBeingDragged = false;
    }

}

I had to use the UIElement's AddHandler method to register MouseUp because somehow it has being marked as Handled (the AddHandler method allows you to register an event handler for events that have been handled previously, ieeHandled = true) 我必须使用UIElement的AddHandler方法来注册MouseUp,因为以某种方式将它标记为Handled(AddHandler方法允许您为以前已处理的事件注册事件处理程序,即ieHandled = true)

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

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