【发布时间】:2011-12-07 00:21:19
【问题描述】:
一段时间以来,我一直在使用 WPF 和 C# 非常成功地实现基本的拖放功能。我在实现它之后总是遇到一个问题......由于某种原因,拖放功能会阻止ListBoxItems 被选中(在第一次点击时)。
如果我单击 ListBoxItem 但不拖动它,它不会被选中,并且会立即出现拖动图标。在下一次单击时,我可以选择任何ListBoxItems,并且不会出现拖动图标。这个循环然后重复......第一次点击不会选择,第二次会。
下面是我的拖放代码的典型实现,摘自 Micorsoft MCTS 70-511 'Training kit' book。
private void ListBox_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e)
{
object data = (ListBoxItem)(FrameworkElement)sender;
if (data != null) DragDrop.DoDragDrop(ListBox, data, DragDropEffects.Copy);
e.Handled = false;
}
private void ListBox_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(ListBoxItem))) e.Effects = DragDropEffects.Copy;
}
private void ListBox_Drop(object sender, DragEventArgs e)
{
object data = e.Data.GetData(typeof(ListBoxItem));
if (data != null) DoSomethingWith((DataType)((ListBoxItem)data).DataContext);
}
拖放工作正常,但项目选择没有......我假设通过在ListBox_PreviewMouseLeftButtonDown处理程序中添加e.Handled = false,ListBoxItem选择机制可以处理点击事件,但它永远不会到达那一步。
我还尝试在PreviewMouseLeftButtonDown 处理程序中处理MouseLeftButtonDown 处理程序中的拖动启动,但ListBoxItem 选择机制处理单击事件并且它从未到达该拖放处理程序。
必须有一种方法来启动拖放操作,并且仍然选中了被点击的ListBoxItem,但我仍然没有找到它......任何线索任何人?
更新>>>
感谢 MSDN 文章 @icebat 提供的链接,我已经设法让拖放功能完美运行。现在是这样的:
private void SourceListBox_MouseMove(object sender, MouseButtonEventArgs e)
{
if (e.LeftButton == MouseButtonState.Pressed)
{
object data = ((ListBox)(FrameworkElement)sender).SelectedItem;
if (data != null)
DragDrop.DoDragDrop(SourceListBox, data, DragDropEffects.Copy);
}
}
private void TargetListBox_DragOver(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(typeof(DragObject))) e.Effects = DragDropEffects.Copy;
}
private void TargetListBox_Drop(object sender, DragEventArgs e)
{
object data = e.Data.GetData(typeof(DragObject));
if (data != null) DoSomethingWith((DragObject)data);
}
【问题讨论】:
标签: wpf drag-and-drop selection listboxitem