From 8032f82934445eb90d732184a416a48f32fedbaf Mon Sep 17 00:00:00 2001 From: Kevin Sommer Date: Thu, 3 Oct 2024 12:13:52 +0200 Subject: [PATCH] Check if expected format is available --- .../ContextDropBehavior.cs | 34 ++++++++++++++++++- 1 file changed, 33 insertions(+), 1 deletion(-) diff --git a/src/Avalonia.Xaml.Interactions.DragAndDrop/ContextDropBehavior.cs b/src/Avalonia.Xaml.Interactions.DragAndDrop/ContextDropBehavior.cs index 8d689edb..e16d6f9d 100644 --- a/src/Avalonia.Xaml.Interactions.DragAndDrop/ContextDropBehavior.cs +++ b/src/Avalonia.Xaml.Interactions.DragAndDrop/ContextDropBehavior.cs @@ -1,4 +1,5 @@ -using Avalonia.Controls; +using System.Linq; +using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Xaml.Interactivity; @@ -52,6 +53,7 @@ protected override void OnAttachedToVisualTree() { DragDrop.SetAllowDrop(AssociatedObject, true); } + AssociatedObject?.AddHandler(DragDrop.DragEnterEvent, DragEnter); AssociatedObject?.AddHandler(DragDrop.DragLeaveEvent, DragLeave); AssociatedObject?.AddHandler(DragDrop.DragOverEvent, DragOver); @@ -65,6 +67,7 @@ protected override void OnDetachedFromVisualTree() { DragDrop.SetAllowDrop(AssociatedObject, false); } + AssociatedObject?.RemoveHandler(DragDrop.DragEnterEvent, DragEnter); AssociatedObject?.RemoveHandler(DragDrop.DragLeaveEvent, DragLeave); AssociatedObject?.RemoveHandler(DragDrop.DragOverEvent, DragOver); @@ -73,6 +76,11 @@ protected override void OnDetachedFromVisualTree() private void DragEnter(object? sender, DragEventArgs e) { + if (!IsExpectedFormatAvailable(e)) + { + return; + } + var sourceContext = e.Data.Get(ContextDropBehavior.DataFormat); var targetContext = Context ?? AssociatedObject?.DataContext; Handler?.Enter(sender, e, sourceContext, targetContext); @@ -85,6 +93,11 @@ private void DragLeave(object? sender, RoutedEventArgs e) private void DragOver(object? sender, DragEventArgs e) { + if (!IsExpectedFormatAvailable(e)) + { + return; + } + var sourceContext = e.Data.Get(ContextDropBehavior.DataFormat); var targetContext = Context ?? AssociatedObject?.DataContext; Handler?.Over(sender, e, sourceContext, targetContext); @@ -92,8 +105,27 @@ private void DragOver(object? sender, DragEventArgs e) private void Drop(object? sender, DragEventArgs e) { + if (!IsExpectedFormatAvailable(e)) + { + return; + } + var sourceContext = e.Data.Get(ContextDropBehavior.DataFormat); var targetContext = Context ?? AssociatedObject?.DataContext; Handler?.Drop(sender, e, sourceContext, targetContext); } + + + private static bool IsExpectedFormatAvailable(DragEventArgs e) + { + var availableFormats = e.Data.GetDataFormats(); + if (availableFormats.Contains(ContextDropBehavior.DataFormat)) + { + return true; + } + + e.Handled = true; + e.DragEffects = DragDropEffects.None; + return false; + } }