我们使用模板,这样ListBoxItem的Content中都是我们自定义的数据
<ListBox BorderThickness="1"
Style="{StaticResource CustomListBoxStyle}"
ItemContainerStyle="{StaticResource ComponentInfoStyle}"
ItemsSource="{Binding ComponentList}"
BorderBrush="#eaeaeb"
PreviewMouseDoubleClick="ListBox_OnPreMouseDoubleClick"
PreviewMouseMove="ListBox_OnPreviewMouseMove"
Drop="ListBox_OnDrop"
AllowDrop="True"
Margin="2"/>
c#
我们先用Bind定义数据集合
public ObservableCollection<ComponentInfo> ComponentList1
{
get { return _componentList1; }
set
{
_componentList1 = value;
NotifyChanged("ComponentList1");
}
}
然后在鼠标的Drop ,PreviewMouseMove事件中操作
/// <summary>
/// 鼠标拖动
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void ListBox_OnPreviewMouseMove(object sender, MouseEventArgs e)
{
ListBox cusListBox = sender as ListBox;
if (e.LeftButton == MouseButtonState.Pressed)
{
var pos = e.GetPosition(cusListBox);
HitTestResult result = VisualTreeHelper.HitTest(cusListBox, pos);
if (result == null)
{
return;
}
var listBoxItem = Utils.FindVisualParent<ListBoxItem>(result.VisualHit);
if (listBoxItem == null || listBoxItem.Content != cusListBox.SelectedItem)
{
return;
}
DataObject dataObj = new DataObject(listBoxItem.Content);
DragDrop.DoDragDrop(cusListBox, dataObj, DragDropEffects.Move);
}
e.Handled = true;
}
private void ListBox_OnDrop(object sender, DragEventArgs e)
{
ListBox LBoxSort = sender as ListBox;
var pos = e.GetPosition(LBoxSort);
var result = VisualTreeHelper.HitTest(LBoxSort, pos);
if (result == null)
{
return;
}
//查找元数据 ,ComponentInfo是我们自定义的数据
var sourceComponentInfo = e.Data.GetData(typeof(ComponentInfo)) as ComponentInfo;
if (sourceComponentInfo == null)
{
return;
}
//查找目标数据
var listBoxItem = Utils.FindVisualParent<ListBoxItem>(result.VisualHit);
if (listBoxItem == null)
{
return;
}
var targetComponentInfo = listBoxItem.Content as ComponentInfo;
if (ReferenceEquals(targetComponentInfo, sourceComponentInfo) || targetComponentInfo == null)
{
return;
}
int removeIndex = LBoxSort.Items.IndexOf(sourceComponentInfo);
int targetIndex = LBoxSort.Items.IndexOf(targetComponentInfo);
if (removeIndex < targetIndex)
{
ComponentList1.Insert(targetIndex + 1, sourceComponentInfo);
ComponentList1.RemoveAt(removeIndex);
}
else
{
int remIdx = removeIndex + 1;
if (LBoxSort.Items.Count + 1 > remIdx)
{
ComponentList1.Insert(targetIndex, sourceComponentInfo);
ComponentList1.RemoveAt(remIdx);
}
}
}
}
}
internal static class Utils
{
/// <summary>
/// 根据子元素查找父元素
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static T FindVisualParent<T>(DependencyObject obj) where T : class
{
while (obj != null)
{
if (obj is T)
return obj as T;
obj = VisualTreeHelper.GetParent(obj);
}
return null;
}
}