切换导航
{{systemName}}
{{ info.Title }}
{{info.Title}}
{{ menu.Title }}
{{menu.Title}}
登录
|
退出
搜索
WPF拖拽ListBox中的Item
作者:ych
### WPF列表拖拽 #### 需求一 两个ListBox,拖拽其中一个ListBox的Item,放置到另一个ListBox中 参考 http://www.c-sharpcorner.com/uploadfile/dpatra/drag-and-drop-item-in-listbox-in-wpf/ 右边ListBox2本来是空的,从左边ListBox1中拖拽了一个Item过去。 #### 需求二 单个ListBox,拖拽Item,释放后Item插入到鼠标所在位置,使ListBox的Items排序发生改变 尝试使用ObservableCollection创建一个 ``` ObservableCollection
_empList = new ObservableCollection
(); public Window1() { InitializeComponent(); _empList .Add(new Emp("1", 22)); _empList .Add(new Emp("2", 18)); _empList .Add(new Emp("3", 29)); _empList .Add(new Emp("4", 9)); _empList .Add(new Emp("5", 29)); _empList .Add(new Emp("6", 9)); listbox1.DisplayMemberPath = "Name"; listbox1.ItemsSource = _empList; Style itemContainerStyle = new Style(typeof(ListBoxItem)); itemContainerStyle.Setters.Add(new Setter(ListBoxItem.AllowDropProperty, true)); itemContainerStyle.Setters.Add(new EventSetter(ListBoxItem.PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(s_PreviewMouseLeftButtonDown))); itemContainerStyle.Setters.Add(new EventSetter(ListBoxItem.DropEvent, new DragEventHandler(listbox1_Drop))); listbox1.ItemContainerStyle = itemContainerStyle; } ``` 拖放过程: ``` void s_PreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e) { if (sender is ListBoxItem) { ListBoxItem draggedItem = sender as ListBoxItem; DragDrop.DoDragDrop(draggedItem, draggedItem.DataContext, DragDropEffects.Move); draggedItem.IsSelected = true; } } void listbox1_Drop(object sender, DragEventArgs e) { Emp droppedData = e.Data.GetData(typeof(Emp)) as Emp; Emp target = ((ListBoxItem)(sender)).DataContext as Emp; int removedIdx = listbox1.Items.IndexOf(droppedData); int targetIdx = listbox1.Items.IndexOf(target); if (removedIdx < targetIdx) { _empList.Insert(targetIdx + 1, droppedData); _empList.RemoveAt(removedIdx); } else { int remIdx = removedIdx+1; if (_empList.Count + 1 > remIdx) { _empList.Insert(targetIdx, droppedData); _empList.RemoveAt(remIdx); } } } ``` 参考 https://stackoverflow.com/questions/3350187/wpf-c-rearrange-items-in-listbox-via-drag-and-drop 本来Item排序是从1到6的,拖拽5号Item以改变它在列表中的排序位置。 #### 案例参考 [wpf-drag-item-in-listbox](https://www.cnblogs.com/guxin/p/wpf-drag-item-in-listbox.html "wpf-drag-item-in-listbox")
评论区
先去登录
版权所有:机遇屋在线 Copyright © 2021-2025 jiyuwu Co., Ltd.
鲁ICP备16042261号-1