Search code examples
.netwpfmvvmdrag-and-drop

How to handle drag/drop without violating MVVM principals?


Currently I have in my XAML

<TabControl  
    AllowDrop="True"
    PreviewDragOver="DragOver"
    PreviewDrop="Drop" />

All of my drag/drop code exists within the codebehind of my View, rather than within my ViewModel.

How can I handle drag/drop in my ViewModel without adding any dependencies on the View?


Solution

  • There are libraries for this such as gong and similar snippets on various blog articles.

    However, you shouldn't get too hung up on having absolutely no code-behind. For example, this is still MVVM in my book:

    void ButtonClicked(object sender, EventArgs e)
    {
        ((MyViewModel) this.DataContext).DoSomething();
    }
    

    A command binding might be a better choice, but the logic is definitely in the viewmodel. With something like Drag and Drop, it's more variable where you want to draw the line. You can have code-behind interpret the Drag Args and call methods on the viewmodel when appropriate.