使用拖放框架。要拖動的對象指定為 DragSource,放置目標指定為 DropTarget。在 Drop 事件的事件處理程序中,從拖動源中移除被拖動的元素並將其添加到拖動目標中。
下面是在 ListView 之間拖放的代碼示例。相同的概念可以用於實現其他控件,無論它們是相同的還是不同的控件。
Realization image
DragSource
由於我們要拖動左側的 ListView 項,因此請為左側的 ListView 項指定 DragSource(第 14 至 17 行)
<Grid><Grid.ColumnDefinitions><ColumnDefinition Width="*"/><ColumnDefinition Width="*"/></Grid.ColumnDefinitions><!-- 左側ListView --><ListView Grid.Column="0" ItemsSource="{Binding Tasks1}" Margin="10" BorderBrush="Black" BorderThickness="2"><ListView.ItemTemplate><DataTemplate><Border BorderBrush="LightGray" Background="White" BorderThickness="2" Margin="0,0,-1,2" >...<!--DragSource追加--><ig:DragDropManager.DragSource><ig:DragSource IsDraggable="True" DragChannels="ChannelA" Drop="DragSource_Drop"></ig:DragSource></ig:DragDropManager.DragSource></Border></DataTemplate></ListView.ItemTemplate></ListView><!-- 右側ListView --><ListView Grid.Column="1" ItemsSource="{Binding Tasks2}" Margin="10" BorderBrush="Black" BorderThickness="2">...</ListView></Grid>
Drop Target
由於我們要在右側的 ListView 上放置,因此為右側的 ListView 設置 DropTarget(第 18-21 行)
<Grid>
<Grid.ColumnDefinitions><ColumnDefinition Width="*"/><ColumnDefinition Width="*"/></Grid.ColumnDefinitions><!-- 左側ListView --><ListView Grid.Column="0" ItemsSource="{Binding Tasks1}" Margin="10" BorderBrush="Black" BorderThickness="2">...</ListView><!-- 右側ListView --><ListView Grid.Column="1" ItemsSource="{Binding Tasks2}" Margin="10" BorderBrush="Black" BorderThickness="2">...</ListView.ItemTemplate><!-- DropTarget追加 --><ig:DragDropManager.DropTarget><ig:DropTarget IsDropTarget="True" DropChannels="ChannelA"></ig:DropTarget></ig:DragDropManager.DropTarget></ListView></Grid>
請注意,我將 DropTarget 設置為 ListView,而不是 ListView 的項目。
必須為可視化樹中的 UI 元素設置 DragSource 和 DropTarget。如果在這裡將DropTarget 設置為ListView item,當ListView 為空時,將無法進行drop。為避免這種情況,我在 ListView 本身上設置了 DropTarget。
Drop event handler
取出被拖動項的實例,每個拖動源和放置目標ListViews,以及綁定到每個拖動源和放置目標ListViews的集合,從拖動源集合中移除被拖動項,並返回放置目標Add到集合。
private void DragSource_Drop(object sender, Infragistics.DragDrop.DropEventArgs e){Border sourcePanel = e.DragSource as Border;TaskItem sourceTask = sourcePanel.DataContext as TaskItem;ListView sourceListView = Utilities.GetAncestorFromType(sourcePanel, typeof(ListView), false) as ListView;ListView targetListView = e.DropTarget as ListView;ObservableCollection<TaskItem> sourceTasks = sourceListView.ItemsSource as ObservableCollection<TaskItem>;ObservableCollection<TaskItem> targetTasks = targetListView.ItemsSource as ObservableCollection<TaskItem>;sourceTasks.Remove(sourceTask);targetTasks.Add(sourceTask);}
這次,ListView 的 ItemsSource 綁定到視圖模型的集合,因此從拖動源中刪除和添加項目是是為了綁定源的集合實現的。
如果您只是想交換控件在視圖上的位置,您也可以這樣做。在這種情況下,將拖動的控件從原始父控件中移除,並將其作為子控件添加到放置目標控件中。