Search code examples
c#wpfline

Line (Crosshair) in WPF not updating when coordinates are updated with mouse move event - C#


I'm trying to create a cross-hair out of two lines on a WPF canvas.

I'm finding that when I initialize the lines they draw correctly. But when I update the coordinates of the lines using the mouse move event, the lines are not updating.

Why are the lines not updating when the coordinates of the point `currentMousePoint are updated?

public CADControl()
    {
        InitializeComponent();
    }
    
    //(500, 500) added just to test the lines appear which they do.
    private Point currentMousePoint = new Point(500,500);

    private void CadCanvas_MouseMove(object sender, MouseEventArgs e)
    {
        currentMousePoint = e.GetPosition(this);
        //coordinates appear to update correctly in the console
        Console.WriteLine("x: " + currentMousePoint.X + "  y: " + currentMousePoint.Y);
        InvalidateVisual();
        UpdateLayout();
    }

    private double screenWidth;
    private double screenHeight;

    private void DrawCursorCrosshair()
    {
        screenWidth = CadCanvas.ActualWidth;
        screenHeight = CadCanvas.ActualHeight;

        Line horizontalLine = new Line();
        horizontalLine.Stroke = Brushes.White;
        horizontalLine.X1 = 0;
        horizontalLine.X2 = screenWidth;
        horizontalLine.Y1 = currentMousePoint.X;
        horizontalLine.Y2 = currentMousePoint.X;

        CadCanvas.Children.Add(horizontalLine);

        Line verticalLine = new Line();
        verticalLine.Stroke = Brushes.White;
        verticalLine.X1 = currentMousePoint.X;
        verticalLine.X2 = currentMousePoint.X;
        verticalLine.Y1 = 0;
        verticalLine.Y2 = screenHeight;

        CadCanvas.Children.Add(verticalLine);

    }

    private void CadCanvas_Loaded(object sender, RoutedEventArgs e)
    {
        DrawCursorCrosshair();
    }

Solution

  • You need to store the reference to your lines and update them in the MouseMove event handler:

    private Line _v;
    private Line _h;
    

    add in DrawCursorCrosshair:

    _h = horizontalLine;
    _v = verticalLine;
    

    and in CadCanvas_MouseMove (after currentMousePoint is updated):

    Canvas.SetLeft(_v, currentMousePoint.X);
    Canvas.SetTop(_h, currentMousePoint.Y);
    

    and set a static position to the lines in DrawCursorCrosshair:

    verticalLine.X1 = 0;
    verticalLine.X2 = 0;
    
    horizontalLine.Y1 = 0;
    horizontalLine.Y2 = 0;