1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > ListBox实现拖拽排序功能

ListBox实现拖拽排序功能

时间:2018-11-17 17:57:01

相关推荐

ListBox实现拖拽排序功能

1、拖拽需要实现的事件包括:

PreviewMouseLeftButtonDown

LBoxSort_OnDrop

具体实现如下:

private void LBoxSort_OnPreviewMouseLeftButtonDown(object sender, MouseButtonEventArgs e){var pos = e.GetPosition(LBoxSort);HitTestResult result = VisualTreeHelper.HitTest(LBoxSort, pos);if (result == null){return;}var listBoxItem = Utils.FindVisualParent<ListBoxItem>(result.VisualHit);if (listBoxItem == null || listBoxItem.Content != LBoxSort.SelectedItem){return;}DataObject dataObj = new DataObject(listBoxItem.Content as Person);DragDrop.DoDragDrop(LBoxSort, dataObj, DragDropEffects.Move);}private void LBoxSort_OnDrop(object sender, DragEventArgs e){var pos = e.GetPosition(LBoxSort);var result = VisualTreeHelper.HitTest(LBoxSort, pos);if (result == null){return;}//查找元数据var sourcePerson = e.Data.GetData(typeof (Person)) as Person;if (sourcePerson == null){return;}//查找目标数据var listBoxItem = Utils.FindVisualParent<ListBoxItem>(result.VisualHit);if (listBoxItem == null){return;}var targetPerson = listBoxItem.Content as Person;if (ReferenceEquals(targetPerson, sourcePerson)){return;}_persons.Remove(sourcePerson);_persons.Insert(_persons.IndexOf(targetPerson), sourcePerson);}}

事件实现

2、排序功能实现:

数据源:

private ObservableCollection<Person> _persons = new ObservableCollection<Person>();private void InitData(){_persons.Add(new Person{Name = "test1", Order = "1"});_persons.Add(new Person { Name = "test2", Order = "2" });_persons.Add(new Person { Name = "test3", Order = "3" });_persons.Add(new Person { Name = "test4", Order = "4" });_persons.Add(new Person { Name = "test5", Order = "5" });}

数据源

3、排序功能实现:

为数据集合实现CollectionChanged事件,当数据集合发生变化时执行:

private void PersonsOnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e){if (e.Action == NotifyCollectionChangedAction.Remove){for (int i = e.OldStartingIndex; i < _persons.Count; i++){_persons[i].Order = i.ToString();}}else if (e.Action == NotifyCollectionChangedAction.Add){for (int i = e.NewStartingIndex; i < _persons.Count; i++){_persons[i].Order = i.ToString();}}}

排序

4、相关代码附加:

public class Person : INotifyPropertyChanged{public string Name { get; set; }private string _order;public string Order{get { return _order; }set { _order = value; OnPropertyChanged("Order"); }}public event PropertyChangedEventHandler PropertyChanged;[NotifyPropertyChangedInvocator]protected virtual void OnPropertyChanged([CallerMemberName] string propertyName = null){PropertyChangedEventHandler handler = PropertyChanged;if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));}}internal static class Utils{//根据子元素查找父元素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;}}

相关代码

5、代码下载地址:

/detail/w_wanglei/6375371

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。