在画布上画一条线

时间:2014-01-14 01:23:48

标签: c# wpf

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 }
    });
}

当我调试事件时,永远不会被调用,无论是鼠标向上还是鼠标按下。知道为什么吗?

1 个答案:

答案 0 :(得分:3)

在画布上需要背景才能捕获鼠标,尝试添加透明:

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