2013-07-27 58 views
1

我試圖寫我自己的自定義畫布,並想繪製一個由小矩形組成的迷宮。我的問題是,我只在屏幕上得到4個小點,而不是4個矩形(當用2×2場進行嘗試時)。 下面是一些代碼:自定義畫布的問題

public class LabyrinthCanvas : System.Windows.Controls.Canvas 
{ 
    public static readonly int RectRadius = 60; 

    public ObservableCollection<ObservableCollection<Rect>> Rectangles; 

    public LabyrinthCanvas() 
    { 
     Rectangles = new ObservableCollection<ObservableCollection<Rect>>(); 
    } 

    public void AddRectangles(int Height, int Width) 
    { 
     for (int iHeight = 0; iHeight < Height; iHeight++) 
     { 
      ObservableCollection<Rect> newRects = new ObservableCollection<Rect>(); 
      newRects.CollectionChanged += RectanglesChanged; 
      Rectangles.Add(newRects); 

      for (int iWidth = 0; iWidth < Width; iWidth++) 
      { 
       Rect rect = new Rect(iHeight * RectRadius, iWidth * RectRadius); 
       Rectangles[iHeight].Add(rect); 
      } 
     } 
    } 

    public void RectanglesChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e) 
    { 
     if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add) 
     { 

      foreach (object rect in e.NewItems) 
      { 
       if (rect is Rect) 
       { 
        this.Children.Add(((Rect)rect).innerRectangle); 
        System.Windows.Controls.Canvas.SetTop(((Rect)rect).innerRectangle, ((Rect)rect).YPos); 
        System.Windows.Controls.Canvas.SetLeft(((Rect)rect).innerRectangle, ((Rect)rect).XPos); 
       } 
      } 
     } 
     else if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove) 
     { 
      foreach (Rect rect in e.OldItems) 
      { 
       this.Children.Remove(rect.innerRectangle); 
      } 
     } 
    } 
} 

public class Rect : INotifyPropertyChanged 
{ 
    public Rect(int YPos, int XPos) 
    { 
     innerRectangle.Stroke = System.Windows.Media.Brushes.Black; 
     innerRectangle.Fill = System.Windows.Media.Brushes.Blue; 
     this.YPos = YPos; 
     this.XPos = XPos; 
    } 

    public System.Windows.Shapes.Rectangle innerRectangle = new System.Windows.Shapes.Rectangle(); 

    public int YPos; 
    public int XPos; 
} 

我認爲重要的是:

this.Children.Add(((Rect)rect).innerRectangle); 
        System.Windows.Controls.Canvas.SetTop(((Rect)rect).innerRectangle, ((Rect)rect).YPos); 
        System.Windows.Controls.Canvas.SetLeft(((Rect)rect).innerRectangle, ((Rect)rect).XPos); 

林用自己的類「矩形」,因爲我需要這是我從所示的代碼去掉了一些額外的屬性和我不能從Rectangle繼承。

回答

1

我不完全確定你希望你的最終結果是什麼樣的,所以我可能無法建議你以後的確切解決方案。

也就是說,你在屏幕上獲得小點而不是矩形的原因是因爲畫布在您指定的座標處呈現Rect對象的innerRectangle,但您從未初始化設置尺寸那innerRectangle

您看到的點是那些寬度/無邊框矩形,其中Black描邊描邊(點)。

你可以看到發生了什麼事情,如果你嘗試沿着這些路線的東西:

public System.Windows.Shapes.Rectangle innerRectangle = new System.Windows.Shapes.Rectangle() { Width = 10, Height = 10 };