WPF(二)路由事件5.鼠标拖放

WPF中的拖放操作的方法和事件被集中到System.Windows.DragDrop.

拖放操作通过下面三个步骤进行:

(1)用于单击一个元素,并保持鼠标键为按下状态。这是信息被搁置起来,并且拖放操作开始。

(2)用户将鼠标移动到其他元素上,如果该元素可以接受正在拖动的内容,鼠标指针会变成拖放图标。否则鼠标指针会变成一个禁止的图标。

(3)当用户释放鼠标时,元素接受信息并决定如何处理接受到的信息,在没有释放鼠标时,可以通过按下Esc键取消操作。

Xaml

<Window x:Class="Prj_05_5MouseDragDrop.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 Margin="5">
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBox Padding="10" VerticalAlignment="Center" HorizontalAlignment="Center">拖动内容</TextBox>
<Label Grid.Column="1" Padding="30" Background="LightBlue" VerticalAlignment="Center"
HorizontalAlignment
="Center" MouseDown="lblSource_MouseDown">不接受拖动内容</Label>
<Label Grid.Row="1" Grid.ColumnSpan="2" HorizontalAlignment="Center" Padding="20"
AllowDrop
="True" Drop="lblTarget_Drop">拖动到这</Label>
</Grid>
</Window>

C#

        private void lblSource_MouseDown(object sender, MouseButtonEventArgs e)
{
Label lbl = (Label)sender;
DragDrop.DoDragDrop(lbl, lbl.Content, DragDropEffects.Copy);
}

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


效果图



原文地址:https://www.cnblogs.com/WilliamJiang/p/2350151.html