At the moment, to get the coordinates of the mouse, I use the following approach:

XAML

<interactivity:Interaction.Triggers> <interactivity:EventTrigger EventName="PreviewDragOver"> <i:CallMethodAction MethodName="UIElement_OnPreviewDragOver" TargetObject="{Binding}" /> </interactivity:EventTrigger> </interactivity:Interaction.Triggers> 

VM

 public void UIElement_OnPreviewDragOver(object sender, DragEventArgs e) { Point = e.GetPosition((TreeView)sender); } 

I’m not satisfied with the fact that I’m working inside a VM with a control, and I would like to redo this handler on ICommand . But how then to get the coordinates of the mouse?

  • win32 methods you do not want? - Senior Pomidor
  • @SeniorAutomator, Yes, it seems to me that in this situation, you can do without WinApi . - Lightness
  • one
    Well, in theory, we need a custom implementation of EventToCommand, which will send point to the command point parameter - vitidev
  • More precisely, we need a custom heir to the class TriggerAction<ICommand> - Pavel Mayorov
  • @PavelMayorov, I don’t quite understand how I use TriggerAction<ICommand> - Lightness

1 answer 1

Since the coordinates of the mouse is not so easy to connect via XAML, the easiest way is to make a wrapper in the code-behind. Let your VM command be in the DragCommand property.

In XAML:

 <Grid PreviewDragOver="OnPreviewDragOver" ...> 

In the code behind you need to do this:

We put dependency property not to cast DataContext to type VM .

 public ICommand DragPreviewCommand { get { return (ICommand)GetValue(DragPreviewCommandProperty); } set { SetValue(DragPreviewCommandProperty, value); } } public static readonly DependencyProperty DragPreviewCommandProperty = DependencyProperty.Register("DragPreviewCommand", typeof(ICommand), typeof(MyWindow)); 

In the constructor, we set the binding (in XAML it will not work):

 public MyWindow() { InitializeComponent(); SetBinding(DragPreviewCommandProperty, "DragCommand"); } 

And we define the handler:

 void OnPreviewDragOver(object sender, DragEventArgs e) { var senderUIElement = (UIElement)sender; var mousePosition = e.GetPosition(senderUIElement); var command = DragPreviewCommand; if (command != null) command.Execute(mousePosition); }