Get click position on command binding

What I want to do is a UserControl containing a section with a grid where something happens when you click on the grid. I need the pixel position where the click occurred, and I do it all in MVVM style. I know how I can suggest actions on my ViewModel:

<Grid>
 <Grid.InputBindings>
   <MouseBinding Gesture="LeftClick" Command="{Binding MinimapClick}"/>
 </Grid.InputBindings>
</Grid>

My problem is that I don’t know how to get the coordinates ... any ideas? I appreciate your help!

+5
source share
3 answers

How about this?

private void MinimapClick(object parameter)
{
    Point mousePos = Mouse.GetPosition(myWindow);
}

If you do not have a link to a window, you can send it as a parameter (or use any desired point).

+5
source

KDiTraglia ... ViewModel. , - . xaml:

<Grid Width="100" Height="100" Grid.Column="2" Grid.Row="2" x:Name="TargetGrid">
    <Grid>
        <Grid.InputBindings>
            <MouseBinding Gesture="LeftClick" Command="{Binding Path=TargetClick}" CommandParameter="{Binding ElementName=TargetGrid}" />
        </Grid.InputBindings>
    </Grid>
</Grid>

UserControl ViewModel. ViewModel :

public class PositioningCommand : ICommand
{
    public PositioningCommand()
    {
    }

    public void Execute(object parameter)
    {
        Point mousePos = Mouse.GetPosition((IInputElement)parameter);
        Console.WriteLine("Position: " + mousePos.ToString());
    }

    public bool CanExecute(object parameter) { return true; }

    public event EventHandler CanExecuteChanged;
}

public PositioningCommand TargetClick
{
    get;
    internal set;
}
+12

- click ContextMenu. : ( ) ElementName CommandParameter.

, , , :

    System.Windows.Data Error: 4 : Cannot find source for binding with reference 'ElementName=imgArena'. BindingExpression:(no path); DataItem=null; target element is 'MenuItem' (Name='mnuAddItem'); target property is 'CommandParameter' (type 'Object')

-, WPF , , .

, :

    NameScope.SetNameScope(mnuGrid, NameScope.GetNameScope(this));

"mnuGrid" - .

After that, I was able to transfer my control as a parameter to my team, just like Beta Vulgaris did above.

For reference, my XAML looks like this:

    <Image Name="imgArena" >
        <Image.ContextMenu>
            <ContextMenu Name="mnuGrid">
                <MenuItem Header="Place _Entry" Name="mnuAddItem"
                    Command="{Binding AddEntryCmd}" 
                    CommandParameter="{Binding ElementName=imgArena}" />
            </ContextMenu>
        <Image.ContextMenu>
    </Image>
0
source

All Articles