简体   繁体   中英

Drawing a line in canvas

XAML

<Canvas Name="canvas" MouseDown="canvas_MouseDown" MouseUp="canvas_MouseUp" />

C#

Point P1;
private void canvas_MouseDown(object sender, MouseButtonEventArgs e)
{
    P1 = e.GetPosition(canvas);
}

private void canvas_MouseUp(object sender, MouseButtonEventArgs e)
{
    var P2 = e.GetPosition(canvas);
    canvas.Children.Add(new Line()
    {
        X1 = P1.X,
        Y1 = P1.Y,
        X2 = P2.X,
        Y2 = P2.Y,
        StrokeThickness = 3,
        Stroke = new SolidColorBrush { Color = Colors.Blue }
    });
}

When I debug the events never get called, whether on mouse up or mouse down. Any idea why?

You need a background on the canvas for it to capture mouse, try adding a transparent:

<Canvas Name="canvas" 
        MouseDown="canvas_MouseDown" 
        MouseUp="canvas_MouseUp" 
        Background="Transparent"/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM