0
votes

I am new to WPF. I want to have several different shapes in a canvas, then show a different context menu depending on which shape user right-clicks in. I am presently trying with just one shape, a rectangle inside a canvas. What came to mind was that in the handler for right click I should do a hit test for the rectangle. If it comes back true, I would show the context menu for this shape. But it does not work. How can I detect that the right click is inside the rectangle and not elsewhere on the canvas?

XAML :

<Canvas Grid.Column ="2" Name="canvas" Background="Transparent" RightButtonDown="show_context_menu" >
    <Rectangle Name="myrectangle"  Width="1000" Height="500"  Fill="LightSteelBlue"             Stroke="Black" StrokeThickness="4" Canvas.Left="10" Canvas.Top="100"/>
</Canvas>

C# :

private void show_context_menu(object sender, MouseButtonEventArgs e)
{
            Point pt = e.GetPosition((UIElement)sender);
            HitTestResult result = VisualTreeHelper.HitTest(myrectangle, pt);
            if (result != null)
            {
                ContextMenu cm = cmCanvas as ContextMenu; 
                cm.PlacementTarget = sender as Canvas; 
                cm.IsOpen = true;
            }
}
1

1 Answers

0
votes

Issue is you are calculating point relative to canvas and passing visual as rectangle. Calculate point relative to myrectangle and pass it in HitTest method:

Point pt = e.GetPosition(myrectangle);
HitTestResult result = VisualTreeHelper.HitTest(myrectangle, pt);
if (result != null)
{
   .......
}