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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM