WPF Training - Drag and Drop Trong WPF Part I


Đối với lập trình hiện đại hiện nay, việc hỗ trợ người dùng tối đa cũng như trừu tượng hóa các công việc đến mức gần gủi và dễ hiểu nhất cho người dùng đang là tiêu chí hàng đầu của các nhà phát triển phần mềm, chúng ta có thể thấy lợi ích từ việc mà các ứng dụng hộ trợ Drag-and-Drop, công việc trở nên đơn giản hơn và chân thật hơn, thao tác kéo thả nói lên nhiều ý nghĩa hơn việc nhấn các Button. Và hôm nay, tôi sẽ hướng dẫn cở bản cho việc Implement Drag-and-Drop trong WPF.


Drag drop tuanpham 2





WPF Training - Drag and Drop Trong WPF Part II...

 I> Design UI


Công việc rất đơn giản, chúng ta cần chuẩn bị những thứ như sau

  1. WrapPanel A: nguồn chứa đối tượng - Drag

  2. WrapPanel B: nguồn nhận đối tượng - Drop

  3. Ellipse: Đối tượng được drag-drop


Chúng ta Design như sau

[code language="xml"]
<WrapPanel x:Name="_target" Drop="UIElement_OnDrop" AllowDrop="True"
Background="Chartreuse"/>
<WrapPanel x:Name="_source" MouseMove="MouseMove" Grid.Column="2">
[/code]

Trong đó,

  • "UIElement_OnDrop" là method sẽ được call khi có đối tượng đang được Drag lên _target Panel

  • "MouseMove" là method xử lý cho việc Drag, chúng ta có thể dùng ở nhiều sự kiện khác cũng được như MouseLeftButtonDown="MouseMove".


II> Implement behavior


Chúng ta tiến hành implement cho hai method trên như sau

[code language="csharp"]
#region

using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Shapes;

#endregion

namespace Drag_Drop_Sample
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}

private void MouseMove(object sender, MouseEventArgs e)
{
// Get current obj
var ellipse = e.Source as Ellipse;

if (ellipse != null && e.LeftButton == MouseButtonState.Pressed)
{
// Send obj to target
DragDrop.DoDragDrop(ellipse,ellipse,
DragDropEffects.Move);
}
}

private void UIElement_OnDrop(object sender, DragEventArgs e)
{
// Get obj
var obj = e.Data.GetData(e.Data.GetFormats()[0]) as UIElement;

// Get source and target Panel
var parent = (obj as FrameworkElement).Parent as Panel;
var sendertarget = sender as Panel;

if (obj != null && sendertarget != null && !sendertarget.Children.Contains(obj))
{
parent.Children.Remove(obj);
sendertarget.Children.Add(obj);
}
}
}
}
[/code]

Kết quả:
Drag drop tuanpham
Drag drop tuanpham 2

Source tại đây, chúc các bạn thành công!

Tuân Phạm


Chúc các bạn thành công!
PHẠM TUÂN