从画布中获取矩形

本文关键字:获取 布中 | 更新日期: 2023-09-27 18:23:54

我正在做一个windows phone项目。我想为我的碰撞使用一个函数。

这是我使用的代码:

foreach (Rectangle mrec in mCanvas.Children) 
{
    if (my_ellipse.Margin.Top + my_ellipse.Height > mrec.Margin.Top && my_ellipse.Margin.Top <= mrec.Margin.Top + mrec.Height && my_ellipse.Margin.Left + my_ellipse.Width >= mrec.Margin.Left && my_ellipse.Margin.Left <= mrec.Margin.Left + mrec.Width)
    {
        my_ellipse.Fill = new SolidColorBrush(Colors.Green);
    }
    else
    {
        my_ellipse.Fill = new SolidColorBrush(Colors.White);
    }
}

但是,当我使用它时,foreach循环不仅获取Rectangle元素。它还获取TextBlockEllipse

我希望有人能帮我解决这个问题。

从画布中获取矩形

这里的问题是Children包含的对象不是Rectangle类型,foreach正试图将Children中的每个项强制转换为Rectangle。相反,您需要先测试每个项目是否都是Rectangle

foreach (var child in mCanvas.Children) 
{
    Rectangle mrec = child as Rectangle;
    if(mrec != null)
    {
        // Your logic here
    }
}

或者,您可以使用Enumerable.OfType进行筛选。

foreach (Rectangle mrec in mCanvas.Children.OfType<Rectangle>()) 
{
    // Your logic here
}