WPF简单拖拽功能实现

时间:2023-03-10 06:41:39
WPF简单拖拽功能实现

1.拖放操作有两个方面:源和目标。

2.拖放操作通过以下三个步骤进行:

①用户单击元素,并保持鼠标键为按下状态,启动拖放操作。

②用户将鼠标移到其它元素上。如果该元素可接受正在拖动的内容的类型,鼠标指针会变成拖放图标。

③用户释放鼠标键时,元素接收信息并决定如何处理接收到的信息。在没有释放鼠标键时,可按下Esc键取消该操作。

3.Demo

下面实例是一个界面中分上下两个Label。当鼠标点击并拖拽上方Label到下方时,下方Label显示上方Label的内容。

WPF简单拖拽功能实现

XAML代码:

<Window x:Class="鼠标拖放.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="" Width="">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Label Content="拖放的内容" FontSize="" MouseDown="Label_MouseDown" />
<Label Grid.Row="" AllowDrop="True" Drop="Label_Drop" DragEnter="Label_DragEnter" />
</Grid>
</Window>

XAML后台代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
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 鼠标拖放
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
} private void Label_MouseDown(object sender, MouseButtonEventArgs e)
{
Label lbl = (Label)sender;
DragDrop.DoDragDrop(lbl, lbl.Content, DragDropEffects.Copy);
} private void Label_Drop(object sender, DragEventArgs e)
{
((Label)sender).Content = e.Data.GetData(DataFormats.Text);
} private void Label_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.Text))
{
e.Effects = DragDropEffects.Copy;
}
else
{
e.Effects = DragDropEffects.None;
}
}
}
}