How to subscribe to the DragDrop event using EventToCommandBehavior

1 Answer 29 Views
DragAndDrop
Kostiantyn
Top achievements
Rank 1
Iron
Kostiantyn asked on 14 Nov 2023, 11:08 AM

I'm trying to apply command from ViewModel to events like DragDrop.DragOver

<telerik:RadListBox>
 <telerik:EventToCommandBehavior.EventBindings>
     <telerik:EventBinding EventName="DragDrop.DragOver" Command="{Binding CommandCmd}"/>
 </telerik:EventToCommandBehavior.EventBindings>
</telerik:RadListBox>
But such code will not work. How to do this?

1 Answer, 1 is accepted

Sort by
0
Dinko
Telerik team
answered on 16 Nov 2023, 04:21 PM

Hi Kostiantyn,

The EventToCommandBehavior does not support binding a command from the view model to an attached event, which is the case with the DragDrop.DragOver event. However, this requirement could be achieved with two different approaches.

The first approach is to use an attached property to achieve this behavior. Here is an example of how this could be achieved:

public class ListBoxExtensions
{
	public static readonly DependencyProperty ShouldSubscribeToDragOverEventProperty =
		DependencyProperty.RegisterAttached("ShouldSubscribeToDragOverEvent", typeof(bool), typeof(ListBoxExtensions), new PropertyMetadata(false, OnShouldSubscribeToDragOverEventChanged));

	public static bool GetShouldSubscribeToDragOverEvent(DependencyObject obj)
	{
		return (bool)obj.GetValue(ShouldSubscribeToDragOverEventProperty);
	}

	public static void SetShouldSubscribeToDragOverEvent(DependencyObject obj, bool value)
	{
		obj.SetValue(ShouldSubscribeToDragOverEventProperty, value);
	}

	private static void OnShouldSubscribeToDragOverEventChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
	{
		if ((bool)e.NewValue)
		{
			RadListBox radListBox = (RadListBox)d;

			DragDropManager.AddDragOverHandler(radListBox, OnDragOver);
		}
	}

	private static void OnDragOver(object sender, Telerik.Windows.DragDrop.DragEventArgs e)
	{
		//Execute custom logic
	}

After creating the attached property, you can use it in the Xaml as a property of the RadListBox control:

 <telerik:RadListBox x:Name="listBox"
                     local:ListBoxExtensions.ShouldSubscribeToDragOverEvent="True"/>

The second approach is to create a custom RadListBox class and override the OnDragOver event.

public class CustomRadListBox : RadListBox
{
	protected override void OnDragOver(DragEventArgs e)
	{
		base.OnDragOver(e);

		//Execute custom logic
	}
}

With this being said I prepared sample solutions with these two approaches.

Regards,
Dinko
Progress Telerik

Love the Telerik and Kendo UI products and believe more people should try them? Invite a fellow developer to become a Progress customer and each of you can get a $50 Amazon gift voucher.

Tags
DragAndDrop
Asked by
Kostiantyn
Top achievements
Rank 1
Iron
Answers by
Dinko
Telerik team
Share this question
or