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.