WPF: Opacity and MouseEnter Event

As part of the diagram, I draw several overlapping Shapes, each with Opacity=0.5, as here:

<Grid>
    <Rectangle Fill="Blue" Opacity="0.5" MouseEnter="Rectangle_MouseEnter" />
    <Rectangle Fill="Red" Opacity="0.5" />
</Grid>


private void Rectangle_MouseEnter(object sender, MouseEventArgs e)
  {
     MessageBox.Show("Entered");
  }

When the user enters the shape with the mouse, it is necessary to display some additional information, but the event handler will never be called.

Is there a way to get MouseEnter events for all Shapes, not just the topmost?

+2
source share
1 answer

In your layout, only the topmost rectangle will trigger the MouseEnter event. It completely overlaps the first rectangle.

Try this code for eventHandler:

private void Rectangle_MouseEnter(object sender, MouseEventArgs e)
        {
            if (sender != grid.Children[0])
            {
                var rect = (grid.Children[0] as Rectangle);
                if (rect != null) rect.RaiseEvent(e);
            }
            else
            {
                MessageBox.Show("Entered.");
            }
        }

To do this, you need to sign both rectangles in Rectangle_MouseEnter.

+2

Source: https://habr.com/ru/post/1761907/


All Articles