Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get click position over command binding

Tags:

c#

command

mvvm

wpf

What I want to do is a UserControl containing a section with a grid, where something happens when clicking on the grid. I need the position of the pixel where the click happened and I'm doing all of this MVVM style. I know how I can prompt actions on my ViewModel:

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

My problem is now that I don't know how to retrieve the Coordinates... any ideas? I appreciate your help!

like image 452
beta vulgaris Avatar asked Sep 28 '12 15:09

beta vulgaris


2 Answers

KDiTraglia had the right pointer for me... In any case I had some issues with defining the actions and binding to my ViewModel. I'll post my solution in case someone else has some problems. Here's what I've done in the 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>

I create the UserControl and bind it to the ViewModel. In the ViewModel I implement and create the following command:

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;
}
like image 200
beta vulgaris Avatar answered Nov 02 '22 11:11

beta vulgaris


How about this?

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

If you don't have a reference to the window you could send it as a parameter (or use whatever reference point you want).

like image 43
Kevin DiTraglia Avatar answered Nov 02 '22 13:11

Kevin DiTraglia