2013年1月6日日曜日

Drap and Drop Shapes in WPF


using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;
 
namespace DrapDropDemo
{
    public partial class MainWindow : Window
    {
        private bool isDragging;
 
        public MainWindow()
        {
            InitializeComponent();
 
            var rect = new Rectangle
                {
                    Width = 100,
                    Height = 100,
                    Fill = new SolidColorBrush(Colors.Chartreuse)
                };
            rect.MouseLeftButtonDown += rect_MouseLeftButtonDown;
            rect.MouseLeftButtonUp += rect_MouseLeftButtonUp;
            rect.MouseMove += rect_MouseMove;
            var canvas = new Canvas();
            canvas.Children.Add(rect);
            Content = canvas;
        }
 
        private void rect_MouseMove(object senderMouseEventArgs e)
        {
            if (!isDraggingreturn;
            var rect = sender as Rectangle;
            rect.SetValue(Canvas.LeftPropertye.GetPosition(rect.Parent as Canvas).X - rect.ActualWidth/2);
            rect.SetValue(Canvas.TopPropertye.GetPosition(rect.Parent as Canvas).Y - rect.ActualHeight/2);
        }
 
        private void rect_MouseLeftButtonUp(object senderMouseButtonEventArgs e)
        {
            isDragging = false;
            (sender as Rectangle).ReleaseMouseCapture();
        }
 
        private void rect_MouseLeftButtonDown(object senderMouseButtonEventArgs e)
        {
            isDragging = true;
            (sender as Rectangle).CaptureMouse();
        }
    }
}

0 件のコメント:

コメントを投稿