WPF在画布上添加矩形

时间:2011-07-24 13:57:44

标签: c# wpf

下面的代码不添加矩形。谁能建议我错过了什么? mainCanvas.Children.Add(rectangle[i]);不起作用。
RoomX.Count = 5我可以如何添加所有五个不同宽度和高度的矩形,即RoomX,RoomY

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{
     HProDataContext db = new HProDataContext();

     var RoomX = (from d in db.rooms select d.sizex).ToList();
     var RoomY = (from d in db.rooms select d.sizey).ToList();

     for (int i = 0; i < RoomX.Count; i++)
     {
          var random = new Random();
          var rectangle = new Rectangle()
          {
                Stroke = Brushes.Black,
                Fill = Brushes.SkyBlue,
                Width = Convert.ToDouble(RoomX),
                Height = Convert.ToDouble(RoomY),
                Margin = new Thickness(left: random.NextDouble() * 300,
                                       top: random.NextDouble() * 150,
                                       right: 0,
                                       bottom: 0),
                HorizontalAlignment = HorizontalAlignment.Center,
                VerticalAlignment = VerticalAlignment.Center,
            };
            mainCanvas.Children.Add(rectangle);
     }
}

1 个答案:

答案 0 :(得分:2)

Width = Convert.ToDouble(RoomX),
Height = Convert.ToDouble(RoomY),

你确定这是你想做的吗?你正在将一个列表转换成一个双重列表,这似乎有点不合适。

我认为你需要这样的东西:

Width = Convert.ToDouble(RoomX[i]),
Height = Convert.ToDouble(RoomY[i]),