首页 文章

如何在canvas事件处理程序中设置children属性?

提问于
浏览
0

我有一块帆布,里面会是一个形状 . 该画布有一个 MouseLeftButtonDown 事件处理程序 . 然后,我将画布中的形状移动到新位置,但没有任何反应 .

以下是添加形状的方式:

public MainWindow()
    {
        InitializeComponent();
        Rectangle ShapeRect = new Rectangle() { Width=10,Height=10,Fill=Brushes.Blue};
        Canvas_1.Children.Add(ShapeRect);            
    }

这是事件处理程序:

private void Canvas_1_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
        Canvas c = Canvas_1;
        var firstchild = c.Children[0];
        var RectCopy = c.Children.OfType<Rectangle>().FirstOrDefault();              

        Canvas.SetTop(RectCopy, Canvas.GetTop(RectCopy) + 500);
        Canvas.SetLeft(RectCopy, Canvas.GetLeft(RectCopy) + 500);
    }

我've tested the code and it has no errors and all lines run but clearly have no effect. I think it'由于 RectCopy 不是 ShapeRect 这一事实 . 欢迎任何不同的解决方案或答案 . 谢谢 .

1 回答

  • 0

    在Initialize方法的底部添加以下行:

    Canvas.SetTop(ShapeRect, 0);
    Canvas.SetLeft(ShapeRect, 0);
    

    当你到达你的处理程序时, Canvas.GetTop(...) 的值是 NaN .

相关问题