2011-11-30 49 views
0

我正在創建一個新的用戶控件。我的控件擴展了一個StackPanel,現在由另一個StackPanel組成,我在其中添加了一些Rectangles。我希望內部StackPanel在控件內水平居中,矩形與內部StackPanel的底部垂直對齊。我的代碼在下面,但是它導致內部StackPanel與控件的左側對齊,並且矩形在內部StackPanel的頂部對齊。以編程方式更改的矩形上的Horizo​​ntalAligment不起作用

public partial class ComponentStacker : StackPanel 
{ 
    private StackPanel tokenHolder; 

    public ComponentStacker(int numTokens) 
    { 
     this.Orientation = Orientation.Horizontal; 

     tokenHolder = new StackPanel(); 

     this.Children.Add(tokenHolder); 

     tokenHolder.Background = new SolidColorBrush(Colors.DarkKhaki); 
     tokenHolder.HorizontalAlignment = HorizontalAlignment.Center; 

     for (int i = 0; i < numTokens; i++) 
     { 
      Rectangle rect = new Rectangle(); 
      rect.Width = 15; 
      rect.Height = 10; 
      rect.Margin = new Thickness(5, 5, 5, 0); 
      rect.Fill = new SolidColorBrush(Colors.Red); 
      rect.VerticalAlignment = VerticalAlignment.Bottom; 

      this.tokenHolder.Children.Add(rect); 
     } 

     this.Background = new SolidColorBrush(Colors.Goldenrod); 
     this.Margin = new Thickness(10); 
    } 
} 

回答

0

我的第一個問題是:爲什麼不直接添加矩形到你的stackPanel? 我的意思是沒有tokenHolder的東西和: this.Children.Add(rect); 而不是 this.tokenHolder.Children.Add(rect);

交換機上的代碼讓我對這種事情: http://www.switchonthecode.com/tutorials/wpf-tutorial-creating-a-custom-panel-control

+0

主要是因爲我打算稍後將其他項添加到stackPanel。感謝指針;我沒有立即看到任何關於路線的事情,但會繼續看起來更深。 – aha

+0

事實上,我有很多StackPanel的問題沒有很好地瞭解它的大小/內容/ ...我現在只使用Grid。也許這會解決你的問題。 – GameAlchemist

0

我發現這個問題。這是行:

this.Orientation = Orientation.Horizontal; 

當我將其更改爲Orientation.Vertical,內部tokenPanel很好地居中。

相關問題