[英]how to do drag and drop an item from one listbox to another
是否可以將一個項目從一個Listbox
拖放到另一個Listbox
框中? 不是刪除而是復制。 從此Listbox
。 實際上,我有三個列表框,它們非常相似,我需要能夠將一個項目(每個Listbox
一個)拖放到Listbox
listHero
<ListBox x:Name="listhelmets" Height="214" Width="248" ItemsSource="{Binding ListHelmets}"
IsSynchronizedWithCurrentItem="True" Canvas.Left="464" Canvas.Top="37" PreviewMouseDown="helmet_MouseDown1"
PreviewMouseLeftButtonDown="helmet_PreviewMouseLeftButtonDown" DragLeave="helmet_DragLeave"
PreviewMouseMove="helmet_PreviewMouseMove" SelectedValuePath="protection">
<ListBox.ItemTemplate >
<DataTemplate >
<StackPanel Orientation="Horizontal">
<Image Source="{Binding Path=Image}" Width="56" Height="61"/>
<TextBox Height="30" Width="30">
<Binding Path="protection" />
</TextBox>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
到這個
<ListBox x:Name="listHero" Height="148" Width="158"
<ListBox.ItemTemplate >
<DataTemplate >
<StackPanel Orientation="Horizontal">
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
拖放到第一個列表框:
private void helmet_MouseDown1(object sender, MouseButtonEventArgs e)
{
_startPoint = e.GetPosition(null);
}
private void helmet_PreviewMouseMove(object sender, MouseEventArgs e)
{
Point mousePos = e.GetPosition(null);
Vector diff = _startPoint - mousePos;
if (e.LeftButton == MouseButtonState.Pressed &&
(Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance))
{
var listBox = sender as ListBox;
var listBoxItem = listBox.SelectedItem;
DataObject dragData = new DataObject(_dropIdentifier, listBoxItem);
DragDrop.DoDragDrop(listBox, dragData, DragDropEffects.Move);
}
正如MSDN關於枚舉DragDropEffects
所說 :
為了只復制項目,您應該將值DragDropEffects
從Move
更改為Copy
:
private void helmet_PreviewMouseMove(object sender, MouseEventArgs e)
{
//the code omitted for the brevity
if (e.LeftButton == MouseButtonState.Pressed &&
(Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance ||
Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance))
{
//the code omitted for the brevity
DragDrop.DoDragDrop(listBox, dragData, DragDropEffects.Copy);
}
}
XAML:
<ListBox x:Name="DropList"
Drop="DropList_Drop"
DragEnter="DropList_DragEnter"
AllowDrop="True" />
C#:
private void DropList_DragEnter(object sender, DragEventArgs e)
{
if (!e.Data.GetDataPresent("myFormat") ||
sender == e.Source)
{
e.Effects = DragDropEffects.None;
}
}
private void DropList_Drop(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("myFormat"))
{
Contact contact = e.Data.GetData("myFormat") as Contact;
ListView listView = sender as ListView;
listView.Items.Add(contact);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.