简体   繁体   中英

How to cast UIElement to Rectangle

I have some rectangles stored in Canvas.Children, and when traversing the Canvas.Children, I can use

for (int i=0; i<Canvas.Children.Count; i++)
{
     UIElement ui = Canvas.Children[i];
}

However I don't know how to convert ui into System.Windows.Shapes.Rectangle. Could someone help?

A useful answer can be found in this related question .

Also a useful guide to casting can be found on MSDN here .

Hope this helps.

if(ui is Rectangle)
{
Rectangle rect = (Rectangle)ui;
}

This is based on earlier responses. It might be useful for hit boxes, as in collision=hitBox.IntersectsWith(rectList[rcount]); .

Rect[] rectList;
int rcount = 0; 
for (int i=0;i < CanvasB.Children.Count; i++) {
  UIElement ui = CanvasB.Children[i];
  if (ui is Rectangle) {
    rectList[rcount] = new Rect(
      Canvas.GetLeft(ui), 
      Canvas.GetTop(ui), (double)ui.GetValue(ActualWidthProperty), 
      (double)ui.GetValue(ActualHeightProperty)
    );
    rcount++;
  }
}               

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