How to handle drag/drop without violating MVVM principals?

前端 未结 5 685
时光说笑
时光说笑 2020-12-24 07:40

Currently I have in my XAML


All of

5条回答
  •  甜味超标
    2020-12-24 08:10

    This is just an additional answer that ports @Asheh's answer's to VB.NET for VB developers.

    Imports System.Windows
    
    Interface IFileDragDropTarget
    
        Sub OnFileDrop(ByVal filepaths As String())
    
    End Interface
    
    Public Class FileDragDropHelper
    
        Public Shared Function GetIsFileDragDropEnabled(ByVal obj As DependencyObject) As Boolean
            Return CBool(obj.GetValue(IsFileDragDropEnabledProperty))
        End Function
    
        Public Shared Sub SetIsFileDragDropEnabled(ByVal obj As DependencyObject, ByVal value As Boolean)
            obj.SetValue(IsFileDragDropEnabledProperty, value)
        End Sub
    
        Public Shared Function GetFileDragDropTarget(ByVal obj As DependencyObject) As Boolean
            Return CBool(obj.GetValue(FileDragDropTargetProperty))
        End Function
    
        Public Shared Sub SetFileDragDropTarget(ByVal obj As DependencyObject, ByVal value As Boolean)
            obj.SetValue(FileDragDropTargetProperty, value)
        End Sub
    
        Public Shared ReadOnly IsFileDragDropEnabledProperty As DependencyProperty = DependencyProperty.RegisterAttached("IsFileDragDropEnabled", GetType(Boolean), GetType(FileDragDropHelper), New PropertyMetadata(AddressOf OnFileDragDropEnabled))
    
        Public Shared ReadOnly FileDragDropTargetProperty As DependencyProperty = DependencyProperty.RegisterAttached("FileDragDropTarget", GetType(Object), GetType(FileDragDropHelper), Nothing)
    
        Shared WithEvents control As Windows.Controls.Control
        Private Shared Sub OnFileDragDropEnabled(ByVal d As DependencyObject, ByVal e As DependencyPropertyChangedEventArgs)
            If e.NewValue = e.OldValue Then Return
            control = TryCast(d, Windows.Controls.Control)
            If control IsNot Nothing Then
                AddHandler control.Drop, AddressOf OnDrop
            End If
        End Sub
    
        Private Shared Sub OnDrop(ByVal _sender As Object, ByVal _dragEventArgs As DragEventArgs)
            Dim d As DependencyObject = TryCast(_sender, DependencyObject)
            If d Is Nothing Then Return
            Dim target As Object = d.GetValue(FileDragDropTargetProperty)
            Dim fileTarget As IFileDragDropTarget = TryCast(target, IFileDragDropTarget)
            If fileTarget IsNot Nothing Then
                If _dragEventArgs.Data.GetDataPresent(DataFormats.FileDrop) Then
                    fileTarget.OnFileDrop(CType(_dragEventArgs.Data.GetData(DataFormats.FileDrop), String()))
                End If
            Else
                Throw New Exception("FileDragDropTarget object must be of type IFileDragDropTarget")
            End If
        End Sub
    End Class
    

提交回复
热议问题