c# WPF - problem with MouseLeave event on canvas

36 Views Asked by At

In my C# WPF application for Windows, I have a DockPanel onto which I add a Canvas. The Canvas is basically an editable drawing surface. For the Canvas, I have methods for MouseLeave and MouseEnter which work appropriately under normal drawing operations (e.g. drag the mouse pointer around and it leaves a colored trail). However, I am trying to implement a new function where you can select a pre-existing image and use it to "stamp" the Canvas. For example, select a tree image (of type System.Windows.Controls.Image) and then when you move your mouse over the Canvas, you can see a real time preview of how the stamp will look. Then when you left click, it will apply the Image to the Canvas. All of this works, EXCEPT it is causing problems with the MouseLeave event. When you select an Image to stamp to the Canvas, the preview Image is drawn just below the mouse cursor and (presumably) above the Canvas. So if you have an Image selected and your mouse moves out of the Canvas area, the MouseLeave event does not get triggered. The preview image remains visible outside of the actual Canvas area in non-drawable space. What I would like to happen is that if the mouse leaves the Canvas area, the preview image disappears. And then when the mouse re-enters the Canvas area, it reappears. I'm trying to figure out how to have the application "ignore" the Image underneath the mouse cursor in regards to hit testing and determining when the mouse leaves the Canvas.

I have tried setting the Image.IsHitTestVisible = false, but it makes no difference.

Here is a snippet:

    public class MapViewer : GridCanvas
    {
        public Entity SelectedEntity { get; set; }
        bool drawSelectedEntity;
    
        public MapViewer() : base()
        {
            drawSelectedEntity = false;
            MouseLeave += OnMouseLeave;
            MouseEnter += OnMouseEnter;
        }
            public void OnMouseLeave(object sender, MouseEventArgs e)
            {
                drawSelectedEntity = false; // the preview Image drawn below the mouse cursor blocks this from happening
                InvalidateVisual();
            }
            public void OnMouseEnter(object sender, MouseEventArgs e)
            {
                drawSelectedEntity = true;
                InvalidateVisual();
            }
    
            protected override void OnRender(DrawingContext dc)
            {
                base.OnRender(dc);
    
                if (SelectedEntity != null && drawSelectedEntity)
                {
                    dc.DrawImage(SelectedEntity.DisplayAsset.Image.Source, new Rect(halfX, halfY, SelectedEntity.Dimensions.Width, SelectedEntity.Dimensions.Height));
                }
            }
}
    }
0

There are 0 best solutions below