WPF 드래그앤드랍

어떤 분이 질문을 올리셨길레
궁금해서 해보았다.

연습삼아 ListView에 Button 을 넣어주고 드래그해서 canvas에 놓는 테스트이다.

먼저 Xaml


<Window x:Class="WpfApplication3.Window1"

    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

    Title="Window1" Height="342" Width="300">

    <Grid Height="253" Width="269">

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width="15*" />

            <ColumnDefinition Width="131*" />

        </Grid.ColumnDefinitions>

        <Canvas x:Name="mycanvas"

                DragDrop.DragOver="mycanvas_DragOver"

                DragDrop.DragEnter="Canvas_DragEnter"

                DragDrop.DragLeave="mycanvas_DragLeave"

                Drop="mycanvas_Drop"

                Mouse.MouseMove="Canvas_MouseMove"

                Mouse.MouseEnter="mycanvas_MouseEnter"

                AllowDrop="True"

                Grid.ColumnSpan="2" Margin="0,0,109,0" Background="AliceBlue">

          

        </Canvas>

        <ListView x:Name="mylist" Grid.Column="1" HorizontalAlignment="Right"

                 PreviewMouseLeftButtonDown="mylist_PreviewMouseLeftButtonDown"

                 PreviewMouseMove="mylist_PreviewMouseMove" Width="58">

          

        </ListView>

        <Button Height="23" Margin="0,0,0,-24" Name="button1" VerticalAlignment="Bottom" Grid.Column="1" Click="button1_Click" HorizontalAlignment="Right" Width="81.281">Button</Button>

        <Button Grid.Column="1" Height="23"

                Margin="66,0,100,-24" Name="button2"

              

                VerticalAlignment="Bottom">drag me</Button>

    </Grid>

</Window>



그리고, 코드 비하인드(code-behind)


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 WpfApplication3

{

    /// <summary>

    /// Window1.xaml에 대한 상호 작용 논리

    /// </summary>

    public partial class Window1 : Window

    {

        public Window1()

        {

            InitializeComponent();

        }




        private void Canvas_DragEnter(object sender, DragEventArgs e)

        {

            Console.WriteLine("Drag enter");

            Console.WriteLine(e.Source.ToString());

        }




        private void Canvas_MouseMove(object sender, MouseEventArgs e)

        {

            Console.WriteLine("x: " + e.GetPosition(mycanvas).X

                + ", y : " + e.GetPosition(mycanvas).Y);

        }




        private void button1_Click(object sender, RoutedEventArgs e)

        {

            Button b = new Button();

            b.Content = "Drag me";

            mylist.Items.Add(b);

        }




        private void mycanvas_MouseEnter(object sender, MouseEventArgs e)

        {

            Console.WriteLine("mouse enter");

           

        }




        private void mycanvas_DragOver(object sender, DragEventArgs e)

        {

            Console.WriteLine("mycanvas_DragOver ");

        }







       




        Point startPoint;

        private void mylist_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)

        {

            // Store the mouse position

            startPoint = e.GetPosition(null);

        }




        private void mylist_PreviewMouseMove(object sender, MouseEventArgs e)

        {

            // Get the dragged ListViewItem

            ListView listView = sender as ListView;

            ListViewItem listViewItem = FindAnchestor<ListViewItem>((DependencyObject)e.OriginalSource);




            if (listViewItem == null) return;




            // Find the data behind the ListViewItem

            Button hello = listView.ItemContainerGenerator.

                    ItemFromContainer(listViewItem) as Button;




            // Initialize the drag & drop operation

            DataObject dragData = new DataObject("myFormat", hello);

            DragDrop.DoDragDrop(listViewItem, dragData, DragDropEffects.Move);

        }




        // Helper to search up the VisualTree

        private static T FindAnchestor<T>(DependencyObject current)

            where T : DependencyObject

        {

            do

            {

                if (current is T)

                {

                    return (T)current;

                }

                current = VisualTreeHelper.GetParent(current);

            }

            while (current != null);

            return null;

        }




        private void mycanvas_DragLeave(object sender, DragEventArgs e)

        {

            Console.WriteLine("mycanvas_DragLeave");

            Console.WriteLine((e.Data.GetType()));

        }




        private void mycanvas_Drop(object sender, DragEventArgs e)

        {

            Console.WriteLine("Drop");

            Console.WriteLine((e.Data.GetData("myFormat") as Button).Content);

        }

    }

}



요점은 DataObject 만들어서 DoDragDrop  해줘야 canvas에서 AllowDrop 를 true했을때
drag관련 이벤트가 제대로 발생된다.

댓글

이 블로그의 인기 게시물

C#에서 포인터 사용

WPF RichTextBox 와 Document의 바인딩

WPF 이미지위에 라인 그리기(WPF DrawLine on exist Image)