代码改变世界

WPF 的拖拽操作(DragDrop)

2013-09-14 14:02  Andrew.Wangxu  阅读(4676)  评论(0编辑  收藏  举报

    在WPF中似乎没有对拖拽操作进行改变,和以前的方式一样。如果曾近在 Windows 窗体应用程序中使用过鼠标拖放,就会发现在 WPF 中的编程接口实际上没有发生变化。重要的区别是用于拖放操作的方法和事件被集中到了 System.Windows.DragDrop 类中,然后供其他类(如 UIElement )使用。

 

    本质上,拖放操作通过以下三个步骤进行:

  1. 用户单击一个元素或选择一个元素特定的区域,并保持鼠标为按下状态。这时,某些信息被搁置起来,并且拖放操作开始。
  2. 用户将鼠标移动到其他元素上。如果该元素可以接受正在拖动的内容类型,鼠标指针会变成拖放图标。否则鼠标指针会变成一个内部有一条线的圆形,表示不可拖入该数据。
  3. 当用户释放鼠标时,元素接收信息并作出决定如何处理接收到的信息。

 

下面是一个示例:

 

C#代码:

        private void lblTarget_Drop_1(object sender, DragEventArgs e)
        {
            lblTarget.Content = e.Data.GetData(DataFormats.Text);
        }

        private void lblTarget_DragEnter_1(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent(DataFormats.Text))
                e.Effects = DragDropEffects.Copy;
            else
                e.Effects = DragDropEffects.None;
        }

        private void Label_MouseDown_1(object sender, MouseButtonEventArgs e)
        {
            DragDrop.DoDragDrop(lblControl, lblControl.Content, DragDropEffects.Copy);
        }

XAML代码:

<Window x:Class="_1019_DragAndDrap.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>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions>
        
        <TextBox Name="txtStr" Padding="10" VerticalAlignment="Center" HorizontalAlignment="Center">Drag from this text</TextBox>
        <Label Name="lblControl" Padding="10" Background="LightGoldenrodYellow" Grid.Column="1" VerticalAlignment="Center" HorizontalAlignment="Center" MouseDown="Label_MouseDown_1">Or this label</Label>
        <Label Name="lblTarget" Padding="10" Background="LightGoldenrodYellow" Grid.ColumnSpan="2" Grid.Row="1" VerticalAlignment="Center" HorizontalAlignment="Center" AllowDrop="True" DragEnter="lblTarget_DragEnter_1" Drop="lblTarget_Drop_1">To this label</Label>
    </Grid>
</Window>

 

源码下载:https://files.cnblogs.com/andrew-blog/1019_DragAndDrap.rar

使用工具:VS2012

参考:http://www.wxzzz.com/?id=131