WPF 使用 SelectionMode Multiple 从 ListBox 拖放

作者:编程家 分类: swift 时间:2025-11-09

WPF中的ListBox控件是一个非常强大的工具,它允许用户选择多个项。而且,ListBox还支持拖放操作,这为用户提供了更多的灵活性和交互性。在本文中,我们将学习如何使用SelectionMode Multiple选项来实现ListBox的拖放功能,并提供相应的案例代码。

首先,让我们看一下如何设置ListBox的SelectionMode属性为Multiple。通过设置SelectionMode属性为Multiple,我们可以允许用户同时选择多个项。这样,用户就可以通过按住Ctrl键并单击鼠标来选择多个项。

xaml

接下来,我们将学习如何使用拖放操作来移动ListBox中的项。为了实现这一点,我们需要为ListBox的每个项设置DragDrop事件处理程序。

xaml

在ListBox的ItemContainerStyle中,我们为PreviewMouseMove和Drop事件定义了事件处理程序。在PreviewMouseMove事件处理程序中,我们使用DragDrop.DoDragDrop方法来开始拖放操作。在Drop事件处理程序中,我们可以处理拖放操作结束后的逻辑。

现在,让我们来看一下具体的案例代码。在此示例中,我们创建了一个ListBox,并向其中添加了几个项。用户可以使用鼠标左键选择多个项,并拖动它们到ListBox的另一个位置。

xaml

在代码中,我们为ListBox的每个ListBoxItem定义了PreviewMouseMove和Drop事件处理程序。

csharp

private void ListBoxItem_PreviewMouseMove(object sender, MouseEventArgs e)

{

if (e.LeftButton == MouseButtonState.Pressed)

{

ListBoxItem listBoxItem = sender as ListBoxItem;

DragDrop.DoDragDrop(listBoxItem, listBoxItem.DataContext, DragDropEffects.Move);

}

}

private void ListBoxItem_Drop(object sender, DragEventArgs e)

{

if (e.Data.GetDataPresent(typeof(ListBoxItem)))

{

ListBoxItem sourceItem = e.Data.GetData(typeof(ListBoxItem)) as ListBoxItem;

ListBoxItem targetItem = sender as ListBoxItem;

int sourceIndex = listBox.Items.IndexOf(sourceItem);

int targetIndex = listBox.Items.IndexOf(targetItem);

if (sourceIndex >= 0 && targetIndex >= 0)

{

listBox.Items.RemoveAt(sourceIndex);

listBox.Items.Insert(targetIndex, sourceItem);

}

}

}

在ListBoxItem_PreviewMouseMove事件处理程序中,我们检查鼠标左键是否按下,并使用DragDrop.DoDragDrop方法来开始拖放操作。在ListBoxItem_Drop事件处理程序中,我们获取源项和目标项的索引,并将源项插入到目标项的位置。

通过以上代码和操作,我们实现了使用SelectionMode Multiple选项从ListBox拖放项的功能。用户可以通过选择多个项,并通过拖动它们来改变ListBox中的项的位置。这为用户提供了更直观和灵活的交互方式。