Style itemContainerStyle = new Style(typeof(ListBoxItem));
itemContainerStyle.Setters.Add(new Setter(ListBoxItem.AllowDropProperty, true));
itemContainerStyle.Setters.Add(new EventSetter(ListBoxItem.PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(s_PreviewMouseLeftButtonDown)));
itemContainerStyle.Setters.Add(new EventSetter(ListBoxItem.DropEvent, new DragEventHandler(listbox1_Drop)));
listbox1.ItemContainerStyle = itemContainerStyle;
或者
<Window.Resources>
<Style x:Key="ListBoxDragDrop" TargetType="{x:Type ListBoxItem}">
<Setter Property="AllowDrop" Value="true"/>
<EventSetter Event="PreviewMouseMove" Handler="s_PreviewMouseMoveEvent"/>
<EventSetter Event="Drop" Handler="listbox1_Drop"/>
</Style>
</Window.Resources>
<Grid>
<ListBox x:Name="listbox1" ItemContainerStyle="{StaticResource ListBoxDragDrop}" HorizontalAlignment="Left" Height="299" Margin="10,10,0,0" VerticalAlignment="Top" Width="224"/>
</Grid>
This is mouse-handler placed in the code-behind of the XAML.
void s_PreviewMouseMoveEvent(object sender, MouseEventArgs e)
{
if (sender is ListBoxItem && e.LeftButton == MouseButtonState.Pressed)
{
ListBoxItem draggedItem = sender as ListBoxItem;
DragDrop.DoDragDrop(draggedItem, draggedItem.DataContext, DragDropEffects.Move);
draggedItem.IsSelected = true;
}
}
参考:
http://www.codeproject.com/Articles/43614/Drag-and-Drop-in-WPF
http://www.codeproject.com/Articles/22855/ListBox-Drag-Drop-using-Attached-Properties