WPF简单拖拽功能实现

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

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

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

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

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

3.Demo

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

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="350" Width="525">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Label Content="拖放的内容" FontSize="20" MouseDown="Label_MouseDown" />
        <Label Grid.Row="1" AllowDrop="True" Drop="Label_Drop" DragEnter="Label_DragEnter" />
    </Grid>
</Window>
View Code

 

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;
            }
        }
    }
}
View Code

 

posted @ 2015-09-22 17:46  及乌及国  阅读(5224)  评论(0编辑  收藏  举报