DataGridDragDropTarget: change icon based on target

I am currently writing a tool to assign entities from one DataGrid to objects in another DataGrid using drag and drop. With some screaming, I got everything to work smoothly, with one minor annoyance: some entities cannot be tied to any other objects that are not reflected in the user interface (for now).

So, the behavior that I want to achieve is as follows: When the user drags the presenter over another object, the icon should change to the icon "You cannot drop this here" if the entities are incompatible.

This is my code (attached to the DataGridDragDropTarget.DragOver event of the target DataGrid ):

 private void DragDropTarget_OnDragOver(object sender, Microsoft.Windows.DragEventArgs e) { var sw = sender as DataGridDragDropTarget; if (sw == null) { return; } if(GetAssignmentCondition(e)) { // TODO: Show link-icon } else { // TODO: Show drop-disabled-icon } } 

What I have tried so far:

I set e.Effects , the DragDropTarget AllowedSourceEffects property and the base ItemDragEventArgs AllowedEffects and Effects to DragDropEffects.None , but to no avail. Googling also did not produce any meaningful results, and I have no ideas.

+4
source share
2 answers

This helps in situations with TextBox and FlowDocument controls, so it should work with a DataGrid .

The key here is to set the event to Handled so that the control does not perform its fraud.

Something like that:

The code is behind (just for demonstration - it is advisable to use another solution compatible with MVVM):

 private void DragDropTarget_DragEnter(object sender, Microsoft.Windows.DragEventArgs e) { var sw = sender as DataGridDragDropTarget; if (sw == null) { return; } if(GetAssignmentCondition(e)) { // TODO: Show link-icon e.Effects = DragDropEffects.Link; } else { // TODO: Show drop-disabled-icon e.Effects = DragDropEffects.None; } // Add this e.Handled = true; } 
+2
source

Changing the Effects property in DragEventArgs in the OnDragOver event OnDragOver without setting the Handled property to true does not work, because, as you can see here, the source code is in DragDropTarget.cs . If OnDragOver not processed ( args.Handled=true; ) in any of the event handlers, args.Effects will revert to args.AllowedEffects .

  protected virtual void OnDragOver(SW.DragEventArgs args) { foreach (SW.DragEventHandler handler in _dragOver) { handler(this, args); if (args.Handled) { return; } } OnDragEvent(args); } protected virtual void OnDragEvent(SW.DragEventArgs args) { SW.DragDropEffects effects = args.AllowedEffects; ///removed for clarity if (!args.Handled && effects != args.AllowedEffects) { args.Effects = effects; // revert back to args.AllowedEffects args.Handled = true; } } 
+1
source

Source: https://habr.com/ru/post/1481425/


All Articles