WPF C#: Rearrange items in listbox via drag and drop

前端 未结 7 1095
你的背包
你的背包 2020-11-27 12:08

I am trying to figure out how to move the items in a pre-populated listbox up and down via mouse drags.

I have looked at the Control.DoDragDrop method from microsof

7条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-27 13:00

    I took dnr3's answer and altered it for implementation in XAML. Same result, just prefer doing what I can in XAML rather than in the code-behind.

    In place of the code-behind:

    Style itemContainerStyle = new Style(typeof(ListBoxItem));
    itemContainerStyle.Setters.Add(new Setter(AllowDropProperty, true));
    itemContainerStyle.Setters.Add(new EventSetter(PreviewMouseLeftButtonDownEvent, new MouseButtonEventHandler(s_PreviewMouseLeftButtonDown)));
    itemContainerStyle.Setters.Add(new EventSetter(DropEvent, new DragEventHandler(listbox1_Drop)));
    listbox1.ItemContainerStyle = itemContainerStyle;
    

    Put this in the XAML:

    
        
    
    
        
    
    

    This is mouse-handler placed in the code-behind of the XAML.

    void s_PreviewMouseMoveEvent(object sender, MouseEventArgs e)
    {
        if (sender is ListBoxItem && e.LeftButton == MouseButtonState.Pressed)
        {
            ListBoxItem draggedItem = sender as ListBoxItem;
            DragDrop.DoDragDrop(draggedItem, draggedItem.DataContext, DragDropEffects.Move);
            draggedItem.IsSelected = true;
        }
    }
    

提交回复
热议问题