【问题标题】:How to cast UIElement to Rectangle如何将 UIElement 转换为矩形
【发布时间】:2020-05-10 10:03:30
【问题描述】:

我在Canvas.Children中存储了一些矩形,在遍历Canvas.Children时可以使用

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

但是我不知道如何将 ui 转换为 System.Windows.Shapes.Rectangle。有人可以帮忙吗?

【问题讨论】:

  • 矩形 rect = Canvas.Children[i] as Rectangle;
  • 我建议你学习 C# 中的强制转换
  • @LuisFilipe,谢谢!我是 C# 的新手

标签: c#


【解决方案1】:

可以在related question 中找到有用的答案。

也可以在 MSDN here 上找到有用的转换指南。

希望这会有所帮助。

【讨论】:

    【解决方案2】:
    if(ui is Rectangle)
    {
    Rectangle rect = (Rectangle)ui;
    }
    

    【讨论】:

      【解决方案3】:

      这是基于之前的回复。它可能对命中框有用,如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++;
        }
      }               
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多