以下分别记录label、listbox、treeview三个控件的拖动示例:

1.对被拖动控件,实现拖动事件,主要是通过各种鼠标事件,实现DragDrop.DoDragDrop方法。

2.对于需要拖动到的目的控件,需要实现AllowDrop="True" Drop="TargetLabel_Drop"

   <Window.Resources>
<Style TargetType="ListBoxItem">
<EventSetter Event="PreviewMouseMove" Handler="ListBox_PreviewMouseMove"/>
</Style>
<Style TargetType="TreeViewItem">
<EventSetter Event="PreviewMouseMove" Handler="TreeView_PreviewMouseMove"/>
</Style> </Window.Resources>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="7*"/>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition Width="3*"/>
</Grid.ColumnDefinitions>
<StackPanel>
<Label Name="Label" Margin="5,10" Content="This is Label" MouseDown="Label_MouseDown"/>
<ListBox Margin="5,10">
<ListBoxItem>000</ListBoxItem>
<ListBoxItem>111</ListBoxItem>
<ListBoxItem>222</ListBoxItem>
</ListBox>
<TreeView Name="treeView" Margin="5,10">
<TreeViewItem Header="aa">
<TreeViewItem Header="00"/>
<TreeViewItem Header="11"/>
<TreeViewItem Header="22"/>
</TreeViewItem>
</TreeView>
<Button Height="30" Margin="5,10" Name="btn" Content="Rest" Click="btn_Click"/>
</StackPanel>
<Rectangle Grid.Column="1" Fill="Red" Width="1"/>
<Label Name="TargetLabel" Grid.Column="2" Content="Come here" Background="AliceBlue" VerticalContentAlignment="Center" HorizontalContentAlignment="Center" AllowDrop="True" Drop="TargetLabel_Drop"/>
</Grid>
  private void TargetLabel_Drop(object sender, DragEventArgs e)
{
var txt = e.Data.GetData(DataFormats.Text);
this.TargetLabel.Content = txt;
} private void btn_Click(object sender, RoutedEventArgs e)
{
this.TargetLabel.Content = "Come here";
} private void Label_MouseDown(object sender, MouseButtonEventArgs e)
{
DragDrop.DoDragDrop(Label, Label.Content, DragDropEffects.Copy);
} private void ListBox_PreviewMouseMove(object sender, MouseEventArgs e)
{
var item = sender as ListBoxItem;
DragDrop.DoDragDrop(item, item.Content, DragDropEffects.Copy);
} private void TreeView_PreviewMouseMove(object sender, MouseEventArgs e)
{
if (e.LeftButton==MouseButtonState.Released)
{
return;
} var t = sender as TreeView;
var x = this.treeView.SelectedItem;
if (x==null)
{
return;
}
var item = x as TreeViewItem;
DragDrop.DoDragDrop(item, item.Header, DragDropEffects.Copy);
}
05-26 12:26