栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

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

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

我试着用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
    事件,因此被拖动的项目看起来好像未被选中
  • 并且为了更容易实现,放置目标是列表框项目而不是列表框本身-为此可能需要更好的解决方案


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/442679.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号