[SOLVED] WPF – show an image and set different clickable areas on it


the case is this one:

I have an image representing a schema, let’s say a cross like the following
cross shape image

I need to include the image in a WPF UserControl and let the user click on each of the branches (red, green or blue…) and, according to the branch selected, do something different.

What would be the best way to solve this?

I tried with canvas but I don’t find a way to trace correctly the background image with shapes (also because the real image is not so simple as the sample cross here)

thanks for any suggestion


It depends on the comlexity of shapes but it is not difficult to find the shape where mouse up event is fired by VisualTreeHelper.HitTest method.

Let’s say there is a Canvas which has two Rectangles inside.

<Canvas Background="Transparent"
    <Rectangle x:Name="Rect1" Canvas.Left="20" Canvas.Top="20"
               Width="20" Height="20" Fill="Red"/>
    <Rectangle x:Name="Rect2" Canvas.Left="80" Canvas.Top="80"
               Width="20" Height="20" Fill="Green"/>

Catching its PreviewMouseUp event, you can tell the Rectangle where that event is fired.

private void Canvas_PreviewMouseUp(object sender, MouseButtonEventArgs e)
    var position = e.GetPosition((IInputElement)sender);
    var result = VisualTreeHelper.HitTest((Visual)sender, position);
    if (result.VisualHit is Rectangle rect)
        Debug.WriteLine($"Hit {rect.Name}");

Answered By – emoacht

Answer Checked By – Pedro (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *