2017-04-04 53 views
-1

我有WrapPanel帶圖標。 我想逐行創建它(每行5個項目)。如何逐行製作WrapPanel項目?

所以,我的代碼:

<WrapPanel Grid.Row="3" 
     Grid.RowSpan="2" 
     Grid.Column="4" 
     x:Name="wpIcons"> 
</WrapPanel> 


foreach(var ic in obj.Icons) 
{ 
    BitmapImage bi = new BitmapImage(); 
    bi.BeginInit(); 
    bi.StreamSource = new MemoryStream(ic.image); 
    bi.EndInit(); 

    Image im = new Image(); 
    im.Source = bi; 
    wpIcons.Children.Add(im); 
} 

所以,通過線工作,但也不行。

如何逐行製作圖標?

+0

爲什麼不使用一個StackPanel呢?你應該看看MVVM模式。在後面的代碼中添加項目是遠遠不夠的。 –

+0

你是什麼意思逐行?它是垂直還是水平? – Parag

+1

「每行5個項目」的要求範圍可以從簡單(限制WrapPanel的寬度,垂直堆棧面板與水平堆棧面板作爲項目或純粹的「UniformGrid」)到[hard](http://stackoverflow.com/a/9770590/1997232)(創建自己的面板)取決於你想要達到的目標。在給定的代碼中,你可以嘗試限制'im.Width',這樣只有'5'圖像適合,然後'6th'將被打包,但是如果窗口被調整大小等等,會發生什麼? – Sinatr

回答

0

要控制單件上有多少物品,建議您使用UniformGrid。 下面是一個例子:

<UniformGrid Columns="2" Rows="2" Name="uniformGrid1" > 
      <Image Source="pic1.jpg"></Image> 
      <Image Source="pic2.jpg"></Image> 
      <Image Source="pic3.jpg"></Image> 
      <Image Source="pic4.jpg"></Image> 
    </UniformGrid> 

在給出的示例照片將在2行,2列顯示(在你的情況,你可以設置行=「5」而不設置列)。您可以根據需要修改列和/或行。

1

如果你想5個項目,每行,你可以指定Image元素的固定寬度和WrapPanel

<WrapPanel x:Name="wpIcons" Grid.Row="3" 
      Grid.RowSpan="2" 
      Grid.Column="4" 
      Width="100"> 
</WrapPanel> 

foreach (var ic in obj.Icons) 
{ 
    BitmapImage bi = new BitmapImage(); 
    bi.BeginInit(); 
    bi.StreamSource = new MemoryStream(ic.image); 
    bi.EndInit(); 

    Image im = new Image(); 
    im.Width = 20; //<-- = 100/5 
    im.Source = bi; 
    wpIcons.Children.Add(im); 
}