N
N
Nikolay Alekseev2019-12-09 12:11:17
WPF
Nikolay Alekseev, 2019-12-09 12:11:17

WPF ListBox how to manually sort a list by dragging and dropping items with the mouse?

Hi all!
There is a list of files displayed in the listbox:

<ListBox ItemsSource="{Binding FileList}" SelectedItem="{Binding CurrentFile}">
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock VerticalAlignment="Center" Text="{Binding Path=Name}"/>
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

There is a need to change the order of the files before giving it further for processing. I thought that the simplest thing is to implement dragging and dropping elements with the mouse.
I know that you can try to use drag and drop events, but all this "event" in this case destroys the whole point of mvvm (well, or I just don't know how to cook it).
I spent the last two days reading the Internet, found a bunch of libraries that implement this, of course, but only according to some logic, they do it between two sheets, and within one I did not find a single solution.
I thought that, probably, I'm just a fool and this is generally the standard functionality of the sheet, but reading the documentation and MSDN did not give an answer to this question.
Can you please tell me where to look?
Thank you in advance!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Foggy Finder, 2019-12-09
@VariusRain

There is a wonderful library that does almost everything for you:
GongSolutions.WPF.DragDrop
All you need in the simplest scenarios is to set permission to drag FROM and TO:

dd:DragDrop.IsDragSource="True"
dd:DragDrop.IsDropTarget="True"

General recommendation:
Here is a minimal example demonstrating that dragging within a list is not a problem.
VM:
public class MainVM
{
    private IEnumerable<FileInfo> GetFiles() =>
        Directory.EnumerateFiles(Directory.GetCurrentDirectory())
                    .Select(path => new FileInfo(path));
    public MainVM()
    {
        FileList = new ObservableCollection<FileInfo>(GetFiles());
    }
    public FileInfo CurrentFile { get; set; }
    public ObservableCollection<FileInfo> FileList { get; }
}

View:
namespace:
list itself:
<ListBox
    dd:DragDrop.IsDragSource="True"
    dd:DragDrop.IsDropTarget="True"
    ItemsSource="{Binding FileList}"
    SelectedItem="{Binding CurrentFile}">
    <ListBox.ItemTemplate>
        <DataTemplate>
            <StackPanel>
                <TextBlock VerticalAlignment="Center" Text="{Binding Name}" />
            </StackPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

Gif with result:
5dee28369295b074649445.gif

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question