C#

WPF C#:通过拖放重新排列列表框中的项目

发布于 2021-02-02 16:09:26

我试图弄清楚如何通过鼠标拖动上下移动预先填充的列表框中的项目。

我已经从Microsoft的api看了Control.DoDragDrop方法,但是我仍然无法执行任何操作。

由于我是视觉工作室环境的新手,我将不胜感激。

关注者
0
被浏览
97
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    我试着用observablecollection创建一个,看看

        ObservableCollection<Emp> _empList = new ObservableCollection<Emp>();
    
        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);
                }
            }
        }
    

    注意:

    • 在实现中很糟糕的一点是,由于它使用了PreviewMouseLeftButtonDown事件,因此被拖动的项目看起来好像未被选中
    • 并且为了更容易实现,放置目标是列表框项目而不是列表框本身-为此可能需要更好的解决方案


推荐阅读
知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看