0

I want to enable the user of my WPF application to dynamically add items to a canvas area. To do this I added a context menu with commmand binding as follows to the canvas:

<Canvas Background="AliceBlue" Name="DensoWorkingArea">
    <Canvas.ContextMenu>
        <ContextMenu>
            <MenuItem Header="Add New Platform" Command="{Binding AddPlatformCommand}" CommandParameter="{Binding ElementName=DensoWorkingArea}">
                <MenuItem.Icon>
                    <Image Source="\ExternalResources\Icons\Plus.ico" />
                </MenuItem.Icon>
            </MenuItem>
        </ContextMenu>
    </Canvas.ContextMenu>
</Canvas>

In my ViewModel I have a RelayCommand:

public ICommand AddPlatformCommand
{
    get
    {
        return addPlatformCommand ?? (addPlatformCommand = new RelayCommand(command => AddPlatformCommandClicked(command)));
    }
}

And the called method looks as follows:

/// <summary>
/// Method to add a new platform to the canvas
/// </summary>
public void AddPlatformCommandClicked(object parameter)
{
    Canvas canvas = parameter as Canvas;
    if (canvas == null) return;
    Point mousePos = Mouse.GetPosition(canvas);
    PlacementConfiguration.EquipmentPlacementList.Add(new EquipmentPlatformModel(new Point(0, 0)));
}

My problem is, that the passed parameter argument is always null. I have already tried to use a relative source as CommandParameter in the XAML which works as I get the context menu as parameter in the method. However I still need to know the mouse position relative to the canvas.

I have also tried to go another route using windows blend however from the click event there, I also couldn't figure out how to get the mouse position within the canvas.

The question is how to get the mouse position in my AddPlatformCommandClicked() method so I can then go on an place the item at the correct position.

Roland Deschain
  • 2,211
  • 19
  • 50
  • `CommandParameter="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Canvas}}}" also didn't work, but I guess this is because the Canvas is no ancestor of the context menu? Not sure... – Roland Deschain Aug 22 '19 at 11:40
  • 3
    Possible duplicate of [pass contextmenu parent as CommandParameter](https://stackoverflow.com/questions/22448749/pass-contextmenu-parent-as-commandparameter) - Found the correct answer in this post. – Roland Deschain Aug 22 '19 at 11:47

0 Answers0