你正在尋找的行爲是WrapPanel
的默認行爲可以從下面的示例中可以看出。
<WrapPanel >
<WrapPanel.Resources>
<Style TargetType="{x:Type Rectangle}">
<Setter Property="Width"
Value="80" />
<Setter Property="Height"
Value="80" />
<Setter Property="Margin"
Value="3" />
<Setter Property="Fill"
Value="#4DB4DD" />
</Style>
</WrapPanel.Resources>
<Rectangle Width="150" />
<Rectangle />
<Rectangle />
<Rectangle />
<Rectangle Width="200"/>
<Rectangle />
<Rectangle />
<Rectangle />
<Rectangle Width="220"/>
<Rectangle />
<Rectangle />
</WrapPanel>
將會產生以下結果:
正如你所看到的,每個項目的寬度榮幸。
您的問題是由於在模板中將WrapPanel
的方向設置爲Vertical
而導致的。這是從上到下佈局的項目,而不是從左到右,這意味着它是您需要設置的Height
屬性(或者您可以恢復到水平佈局,如我的示例中所示)。
將您的輸出與面板設置爲水平方向的截圖進行比較;每行行的最大尺寸爲Rectangle
。不要相信我?嘗試將其中一個Rectangle's
Height
屬性設置爲較大的值,您將觀察到行大小將增加,並且Rectangles
不再垂直排列。
讀你的意見,我覺得上手的最佳方式是做到以下幾點:
- 有一個
WrapPanel
在水平方向上勾畫出其內容。
- 物品應該有制服
Height
。
- 將
WrapPanel
的Height
限制爲一定的大小,以便不會獲得垂直滾動條。
的高度你WrapPanel
應使用下列公式計算出:
((項目的高度+上邊距+下邊距)x行數))
每個項目的寬度也需要一些思考,以便面板將項目像地鐵界面一樣水平放置(排列而不是交錯)。
有兩種瓷磚尺寸;小的寬度是80px,寬的寬度是166px。 大瓦片的寬度計算出這樣的:
(項目寬* 2)+(左邊距+右邊緣)
這確保瓷磚正確排列。
所以現在我的XAML看起來是這樣的:
<ScrollViewer HorizontalScrollBarVisibility="Auto"
VerticalScrollBarVisibility="Disabled">
<StackPanel Orientation="Horizontal"
Margin="10,0">
<StackPanel.Resources>
<Style TargetType="{x:Type Rectangle}">
<Setter Property="Width"
Value="80" />
<Setter Property="Height"
Value="80" />
<Setter Property="Margin"
Value="3" />
<Setter Property="Fill"
Value="#4DB4DD" />
</Style>
<Style TargetType="{x:Type WrapPanel}">
<Setter Property="Margin"
Value="0,0,25,0" />
<Setter Property="MaxWidth"
Value="516" />
</Style>
</StackPanel.Resources>
<WrapPanel Height="258">
<Rectangle Width="166" />
<Rectangle />
<Rectangle Width="166" />
<Rectangle />
<Rectangle Width="166" />
<Rectangle />
<Rectangle />
<Rectangle />
<Rectangle />
<Rectangle Width="166" />
<Rectangle />
</WrapPanel>
<WrapPanel Height="258">
<Rectangle />
<Rectangle Width="166" />
<Rectangle />
<Rectangle />
<Rectangle />
<Rectangle />
<Rectangle />
<Rectangle Width="166" />
<Rectangle />
</WrapPanel>
</StackPanel>
</ScrollViewer>
將會產生以下結果:
這應該給你足夠的信息來開始這個重新因素成完全控制。如果你這樣做,那麼請記住以下幾點:
- 佈局屬性應該被計算,而不是硬編碼(小項的大小,大項目大小,缺口等),所以,如果你想改變,例如,邊距,佈局仍然可以正常工作(IE仍然排列齊整)。
- 我會限制可以顯示的「瓷磚」的數量(在當前的例子中,如果瓷磚不適合佈局,他們只是隱藏,這可能不是你想要的)。
我相當肯定,你可以設置對象的不同高度/寬度在'WrapPanel' - 參見[這裏](http://www.codeproject.com/Articles/30904/WPF-Layouts-A- Visual-Quick-Start)作爲例子。你在做什麼像在ItemsControl裏面使用'WrapPanel'?如果是這樣,您需要在「ItemContainerStyle」中設置高度/寬度,而不是項目本身(參見本文的底部)(http://rachel53461.wordpress.com/2011/09/17/wpf- itemscontrol-example /)示例/解釋) – Rachel
感謝您的指針,是的,我在'ItemsControl'內使用'WrapPanel'.我猜別的東西導致了這個問題。 –
如果在'ItemContainerStyle'中放置'Height' /'Width'不起作用,您可以使用XAML代碼更新您的問題嗎? – Rachel