Search code examples
wpfimagecanvascursorwpf-controls

Prevent cursor flickering when moving image with mouse position, in WPF


I have an image and I am updating its position on the canvas as the mouse moves.

<Popup Name="floatingTip" AllowsTransparency="True" Placement="Relative" 
       PlacementTarget="{Binding ElementName=MainCanvas}">
            <Image Source="{Binding Name}"
                   Width="{Binding Width}"
                   Height="{Binding Height}"/>
</Popup>

When the mouse enters the canvas I disable the cursor:

private void Canvas_MouseEnter(object sender, MouseEventArgs e)
{
   Mouse.OverrideCursor = Cursors.None;
}

While the cursor is moving inside the canvas I update the position of the popup, which contains an image:

private void Canvas_MouseMove(object sender, MouseEventArgs e)
{
    if (!floatingTip.IsOpen && currentTool == "staticBrush") 
    {
        floatingTip.IsOpen = true;

    }

    if (currentTool == "staticBrush" && lvDataBinding.SelectedIndex != -1) 
    {
        Point currentPos = e.GetPosition(this);

        floatingTip.HorizontalOffset = currentPos.X - (cursorImage.Width / 2.0);
        floatingTip.VerticalOffset = currentPos.Y - (cursorImage.Height / 2.0);
        cursorImage.Width = 50;
        cursorImage.Height = 50;

    }     
}

And when the mouse leaves the canvas I set the cursor back to Cursors.Arror.

Everything works fine if the image is not underneath the cursor, that is, if I offset the images position a bit. But if I place the image directly underneath the cursor, the image begins flickering with the arrow cursor (even though the cursor is hidden).


Solution

  • I figured it out. I needed to set IsHitTestVisible to false on the image.