拖放形状

时间:2011-05-26 18:03:49

标签: c# wpf

我在堆叠面板中有一个矩形形状,我想使用WPF用鼠标拖放到网格中! 如果有人可以帮助我,我很感激吗? 谢谢大家。

3 个答案:

答案 0 :(得分:7)

接下来是一个非常简单的实现。它只需处理鼠标按钮向下/向上/移动Rectangle的事件,以便将其与鼠标移动一起定位。没有任何错误检查,也没有任何阻止用户将矩形拖离Canvas并将其留在那里。

XAML:


<Window x:Class="WpfApplication6.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <Grid>
        <Canvas Name="canvas">
            <Rectangle
                Name="rect"
                Width="50"
                Height="50"
                Canvas.Left="0"
                Canvas.Top="0"
                Fill="Red"
                MouseLeftButtonDown="rect_MouseLeftButtonDown"
                MouseLeftButtonUp="rect_MouseLeftButtonUp"
                MouseMove="rect_MouseMove"
                />
        </Canvas>
    </Grid>
</Window>

代码背后:


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApplication6
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private bool _isRectDragInProg;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void rect_MouseLeftButtonDown( object sender, MouseButtonEventArgs e )
        {
            _isRectDragInProg = true;
            rect.CaptureMouse();
        }

        private void rect_MouseLeftButtonUp( object sender, MouseButtonEventArgs e )
        {
            _isRectDragInProg = false;
            rect.ReleaseMouseCapture();
        }

        private void rect_MouseMove( object sender, MouseEventArgs e )
        {
            if( !_isRectDragInProg ) return;

            // get the position of the mouse relative to the Canvas
            var mousePos = e.GetPosition(canvas);

            // center the rect on the mouse
            double left = mousePos.X - (rect.ActualWidth / 2);
            double top = mousePos.Y - (rect.ActualHeight / 2);
            Canvas.SetLeft( rect, left );
            Canvas.SetTop( rect, top );
        }
    }
}

答案 1 :(得分:0)

为了在项目控件中实现拖放,其中项目由画布以外的任何其他布局,我强烈建议您查看Bea Stollnitz solution。这是一个完全可重用的解决方案,可以使用附加属性在任何项目控件之间进行拖放。

更新:鉴于Bea的博客已经消失,还有其他基于她的解决方案的帖子仍然可用:

  1. https://www.codeproject.com/Articles/43614/Drag-and-Drop-in-WPF
  2. http://blogarchive.claritycon.com/blog/2009/03/generic-wpf-drag-and-drop-adorner
  3. https://siderite.blogspot.com/2011/01/mvvm-drag-and-drop-part-1.html

答案 2 :(得分:0)

扩展@Ed S的答案。使用Canvas的问题是,您基本上可以将控件拖到边界之外。如果要确保它不会越界,我创建了一个简单的应用程序,如果您有两个形状,则可以将它们一起移动或单独拖动。当然,我有一个名为ChkDual模式的复选框,用于确定形状是否必须一起移动。您可以根据需要编辑该功能。

<Grid>
<!--Set some height and width as you like-->
     <Canvas x:Name="CnvBarCodeImage" AllowDrop="True">

                                </Canvas>
<Grid>

private void CreateUIShapes(int numberOfWindows)
        {
//If you want multiple shapes put it inside a loop
                Thumb th = null;
                th = new Thumb();
                th.Width = 200;
                th.Height = 100;
                th.Foreground = new SolidColorBrush(Windows.UI.Colors.Transparent);
                th.BorderBrush = Colors.Green;
                th.BorderThickness = new Thickness(3);

                th.DragDelta += (sender, e) => Th_DragDelta(sender, e);
                Canvas.SetLeft(th, 100);
                Canvas.SetTop(th, 80);
               CnvBarCodeImage.Children.Add(th);

        }

 private event Action<Thumb, double, double> ChangeDimensions;
 private void Th_DragDelta(object sender, DragDeltaEventArgs e, List<Dimensions> limitedWindowMovements)
        {
            var selectedDraggableThumb = sender as Thumb;
            double left = (Canvas.GetLeft(selectedDraggableThumb) >= 0) ? Canvas.GetLeft(selectedDraggableThumb) : 0;
            double top = (Canvas.GetTop(selectedDraggableThumb) >= 0) ? Canvas.GetTop(selectedDraggableThumb) : 0;

            if (ChkDualMode.IsChecked == true)
            {
                var otherDraggableThumbs = CnvBarCodeImage.Children.OfType<Thumb>().Where(x => x != selectedDraggableThumb).ToList();
                var maxTopSelected = 0

                var maxLeftSelected = 0;

                //There may be n number of windows.
                foreach (var item in otherDraggableThumbs)
                {
                    //TOP
                    //Canvas.GetTop(SelectedDraggableThumb) <= 0 || Canvas.GetTop(item) <= 0 original.
                    if (Canvas.GetTop(selectedDraggableThumb) <= maxTopSelected || Canvas.GetTop(item) <= maxTopSelected)
                    {
                        if (e.VerticalChange <= 0)
                        {
                            ChangeDimensions -= BarCodeServiceView_ChangeDimensions;
                            return;
                        }
                    }

                    //LEFT
                    //Canvas.GetLeft(SelectedDraggableThumb) <= 0 || Canvas.GetLeft(item) <= 0 original.
                    else if (Canvas.GetLeft(selectedDraggableThumb) <= maxLeftSelected || Canvas.GetLeft(item) <= maxLeftSelected)
                    {
                        if (e.HorizontalChange <= 0)
                        {
                            ChangeDimensions -= BarCodeServiceView_ChangeDimensions;
                            return;
                        }
                    }

                    //RIGHT
                    else if (Canvas.GetLeft(selectedDraggableThumb) >=
                        CnvBarCodeImage.ActualWidth - selectedDraggableThumb.ActualWidth ||
                        Canvas.GetLeft(item) >= CnvBarCodeImage.ActualWidth - item.ActualWidth)
                    //|| Canvas.GetLeft(SelectedDraggableThumb) >= maxRightSelected
                    //|| Canvas.GetLeft(item) >= maxRightSelected)
                    {
                        if (e.HorizontalChange > 0)
                        {
                            ChangeDimensions -= BarCodeServiceView_ChangeDimensions;
                            return;
                        }
                    }


                    //BOTTOM
                    else if (Canvas.GetTop(selectedDraggableThumb) + selectedDraggableThumb.ActualHeight >= CnvBarCodeImage.ActualHeight ||
                            Canvas.GetTop(item) + item.ActualHeight >= CnvBarCodeImage.ActualHeight)
                    {
                        if (e.VerticalChange >= 0)
                        {
                            ChangeDimensions -= BarCodeServiceView_ChangeDimensions;
                            return;
                        }
                    }

                    if (ChangeDimensions == null)
                    {
                        ChangeDimensions += BarCodeServiceView_ChangeDimensions;
                    }

                }

                foreach (var item in otherDraggableThumbs)
                {
                    ChangeDimensions?.Invoke(item, e.HorizontalChange, e.VerticalChange);
                }

                left = (Canvas.GetLeft(selectedDraggableThumb) >= CnvBarCodeImage.ActualWidth) ? CnvBarCodeImage.ActualWidth : left;
                top = (Canvas.GetTop(selectedDraggableThumb) >= CnvBarCodeImage.ActualHeight) ? CnvBarCodeImage.ActualHeight : top;
                Canvas.SetLeft(selectedDraggableThumb, left + e.HorizontalChange);
                Canvas.SetTop(selectedDraggableThumb, top + e.VerticalChange);
            }
            else
            {
                //In single mode limit the movement as well.
                int.TryParse(selectedDraggableThumb.Name, out var indexFromName);
                var limitedDimensionForWindow = limitedWindowMovements[indexFromName];

                var maxTop = limitedDimensionForWindow.MaxTopPossible == null ? 0 : limitedDimensionForWindow.MaxTopPossible;
                var maxLeft = limitedDimensionForWindow.MaxLeftPossible == null ? 0 : limitedDimensionForWindow.MaxLeftPossible;
                var maxRight = limitedDimensionForWindow.MaxRightPossible == null ? CnvBarCodeImage.ActualWidth - selectedDraggableThumb.ActualWidth : limitedDimensionForWindow.MaxRightPossible;
                var maxBottom = limitedDimensionForWindow.MaxBottomPossible == null ? CnvBarCodeImage.ActualHeight - selectedDraggableThumb.ActualHeight : limitedDimensionForWindow.MaxBottomPossible;

                if (Canvas.GetTop(selectedDraggableThumb) <= maxTop)
                {
                    if (e.VerticalChange <= 0)
                    {
                        return;
                    }
                }
                else if (Canvas.GetLeft(selectedDraggableThumb) <= maxLeft)
                {
                    if (e.HorizontalChange <= 0)
                    {
                        return;
                    }
                }
                else if (Canvas.GetLeft(selectedDraggableThumb) >= maxRight)
                {
                    if (e.HorizontalChange >= 0)
                    {
                        return;
                    }
                }
                else if (Canvas.GetTop(selectedDraggableThumb) >= maxBottom)
                {
                    if (e.VerticalChange >= 0)
                    {
                        return;
                    }
                }
                left = (Canvas.GetLeft(selectedDraggableThumb) >= CnvBarCodeImage.ActualWidth) ? CnvBarCodeImage.ActualWidth : left;
                top = (Canvas.GetTop(selectedDraggableThumb) >= CnvBarCodeImage.ActualHeight) ? CnvBarCodeImage.ActualHeight : top;
                Canvas.SetLeft(selectedDraggableThumb, left + e.HorizontalChange);
                Canvas.SetTop(selectedDraggableThumb, top + e.VerticalChange);
            }
        }

        private void BarCodeServiceView_ChangeDimensions(Thumb sender, double arg1, double arg2)
        {
            if (sender != null)
            {
                double left = (Canvas.GetLeft(sender) > 0) ? Canvas.GetLeft(sender) : 0;
                double top = (Canvas.GetTop(sender) > 0) ? Canvas.GetTop(sender) : 0;
                Canvas.SetLeft(sender, left + arg1);
                Canvas.SetTop(sender, top + arg2);
            }
        }