034. Drag & Drop

2021. 11. 17. 18:21·사소한 아이의 소소한 스킬/C#
반응형

Drag & Drop이다.

 

Drag&Drop은 언제해도 복잡한거같다....

 

이해를 별로 하고싶지가 않아서일까.......

 

이번에 적는것도 이해는 잘안하고...그냥 거의 실습위주..............

 

일단... ListView간의 Drag & Drop으로 데이터를 복사하는 부분을 확인해보자.

 

일단 XAML!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<Window x:Class="TestProject.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"      
        xmlns:local="clr-namespace:TestProject"
        mc:Ignorable="d"
        Title="MainWindow" Height="500" Width="650">
    <Window.DataContext>
        <local:ViewModel/>
    </Window.DataContext>
 
    <Grid >
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition Height="50"/>
        </Grid.RowDefinitions>
        
        <Grid Grid.Row="0">
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
 
            <Grid Grid.Column="0">
                <ListView x:Name="LV1" ItemsSource="{Binding VALUE1}"
                          PreviewMouseLeftButtonDown="List_PreviewMouseLeftButtonDown" 
                          PreviewMouseMove="List_MouseMove"/>
            </Grid>
 
            <Grid Grid.Column="1">
                <ListView x:Name="LV2" ItemsSource="{Binding VALUE2}"
          Drop="DropList_Drop" 
          DragEnter="DropList_DragEnter" 
          AllowDrop="True"/>
            </Grid>
        </Grid>
 
        <Grid Grid.Row="1">
            <Grid.ColumnDefinitions>
                <ColumnDefinition/>
                <ColumnDefinition/>
                <ColumnDefinition/>
            </Grid.ColumnDefinitions>
        </Grid>
    </Grid>
</Window>
 
Colored by Color Scripter
cs

 

단순 2개의 ListView를 선언해주고

 

각 ListView에 ViewModel의 데이터를 바인딩.

 

또한 드래그가 가능토록 ButtonDown, Drop, Drag 등의 이벤트들을 선언해준다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
 
 
namespace TestProject
{
    /// <summary>
    /// MainWindow.xaml에 대한 상호 작용 논리
    /// </summary>    
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
 
        public Point startPoint;
 
        private void List_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            // Store the mouse position
            startPoint = e.GetPosition(null);
        }
 
        private void List_MouseMove(object sender, MouseEventArgs e)
        {
            // Get the current mouse position
            Point mousePos = e.GetPosition(null);
            Vector diff = startPoint - mousePos;
 
            if (e.LeftButton == MouseButtonState.Pressed &&
                Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
                Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance)
            {
                // 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
                Car contact = (Car)listView.ItemContainerGenerator.ItemFromContainer(listViewItem);
 
                // Initialize the drag & drop operation
                DataObject dragData = new DataObject("DRAGDROP_FORMAT", contact);
                DragDrop.DoDragDrop(listViewItem, dragData, DragDropEffects.Move);
            }
        }
 
        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 DropList_DragEnter(object sender, DragEventArgs e)
        {
            if (!e.Data.GetDataPresent("DRAGDROP_FORMAT") ||
                sender == e.Source)
            {
                e.Effects = DragDropEffects.None;
            }
        }
 
        private void DropList_Drop(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent("DRAGDROP_FORMAT"))
            {
                Car _car = e.Data.GetData("DRAGDROP_FORMAT") as Car;
 
                /// 가져온 데이터를 바인딩 데이터에 넣어준다.
                ViewModel VM = this.DataContext as ViewModel;
                VM.VALUE2.Add(_car);
            }
        }
    }
}
Colored by Color Scripter
cs

 

선언한 함수들 정보..

 

드래그했을때의 정보를 저장해두고 Drop했을때 바인딩된 정보에 데이터를 삽입해준다.

 

ViewModel

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace TestProject
{
    class ViewModel : INotifyPropertyChanged
    {
        public ViewModel()
        {
            for (int i = 0; i < 10; i++)
            {
                VALUE1.Add(new Car("MODEL 3", CAR_TYPE.ELECTONIC, 4000));
                VALUE1.Add(new Car("MODEL S", CAR_TYPE.ELECTONIC, 10000));
                VALUE1.Add(new Car("MODEL X", CAR_TYPE.ELECTONIC, 10000));
                VALUE1.Add(new Car("LUCID AIR", CAR_TYPE.ELECTONIC, 15000));
                VALUE1.Add(new Car("GOLF", CAR_TYPE.ELECTONIC, 6000));
                VALUE1.Add(new Car("TIROC", CAR_TYPE.GASOLINE, 5000));
                VALUE1.Add(new Car("BMW 3", CAR_TYPE.DIESEL, 6000));
                VALUE1.Add(new Car("BMW 5", CAR_TYPE.DIESEL, 8000));
                VALUE1.Add(new Car("BMW 7", CAR_TYPE.DIESEL, 10000));
                VALUE1.Add(new Car("BENZ B", CAR_TYPE.DIESEL, 4000));
                VALUE1.Add(new Car("BENZ C", CAR_TYPE.DIESEL, 6000));
                VALUE1.Add(new Car("BENZ S", CAR_TYPE.DIESEL, 15000));
                VALUE1.Add(new Car("AUDI A4", CAR_TYPE.DIESEL, 5000));
                VALUE1.Add(new Car("AUDI A6", CAR_TYPE.DIESEL, 7000));
            }
        }
 
        private ObservableCollection<Car> _value1 = new ObservableCollection<Car>();
 
        public ObservableCollection<Car> VALUE1
        {
            get { return _value1; }
            set
            {
                _value1 = value;
                OnPropertyChanged("VALUE1");
            }
        }
 
        private ObservableCollection<Car> _value2 = new ObservableCollection<Car>();
 
        public ObservableCollection<Car> VALUE2
        {
            get { return _value2; }
            set
            {
                _value2 = value;
                OnPropertyChanged("VALUE2");
            }
        }
 
        public event PropertyChangedEventHandler PropertyChanged;
 
        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}
 
Colored by Color Scripter
cs

 

ViewModel은 바인딩하는 데이터 2개가 끝..

 

실행장면

 

 

Drag&Drop은.....아...확인하기 귀차나.....

 

전체 코드는 여기

TestProject.zip
0.17MB

반응형
저작자표시 비영리 변경금지 (새창열림)
'사소한 아이의 소소한 스킬/C#' 카테고리의 다른 글
  • 036. Find Window
  • 035. XmlSerialize
  • 33. ToString Format
  • 032. Filter Grid
JOOJI
JOOJI
그냥 혼자좋아하는 것들 남기는 블로그....
  • JOOJI
    사소한프로그래머의 소소한행복
    JOOJI
  • 전체
    오늘
    어제
    • 분류 전체보기 (951) N
      • 사소한 아이의 소소한 일상 (245)
      • 사소한 아이의 소소한 먹거리 (43)
      • 사소한 아이의 소소한 정보 (75) N
      • 사소한 아이의 소소한 감사 (4)
      • 사소한 아이의 소소한 운동 (53) N
      • 사소한 아이의 소소한 여행 (40)
        • 2013_전주 (1)
        • 2014_독일 (13)
        • 2014_군산 (1)
        • 2015_제주도 (3)
        • 2015_서울모토쇼 (3)
        • 2015_진해 (1)
        • 2015_전주 (1)
        • 2016_여수 (1)
        • 2020_강릉 (1)
        • 2022_제주도 (4)
      • 사소한 아이의 소소한 강짱 (22)
        • 하트투하트 (10)
        • MAPS (1)
        • 화려한 유혹 (2)
        • 한여름의 추억 (2)
      • 사소한 아이의 TV (50)
        • Drama (9)
        • 예능 (32)
        • 사소한 아이의 다현 (9)
      • 사소한 아이의 소소한 스킬 (130)
        • Scaleform (2)
        • C# (74)
        • QT (3)
        • 알고리즘 (4)
        • Python (21)
        • PyQT5 (9)
        • C_C++ (2)
      • 사소한 아이의 소소한 축구 (283)
        • Korea (25)
        • Germany (45)
        • Bayern Munich (64)
        • Soccer_ETC (75)
        • Euro 2016 (12)
        • 친선경기 (3)
      • 사소한 아이의 소소한 생활정보 (6)
  • 블로그 메뉴

    • 홈
    • 태그
    • 미디어로그
    • 위치로그
    • 방명록
    • 관리
  • 링크

    • 독일여행
    • 레바티스토리
    • 프라치노 공간
    • 남성패션꿀템 블로그
  • 공지사항

  • 인기 글

  • 태그

    c#
    python
    러닝
    문제
    회사밥
    뮌헨
    WPF
    분데스리가
    바이에른 뮌헨
    독일
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
JOOJI
034. Drag & Drop
상단으로

티스토리툴바