I am working on a window in which I basically have a listbox (formed out of Binding to an ObservableCollection). These items have an image, title and other stuff. I want to make the listbox (via itemTemplate) to be formed like a matrix of only the images from my ObservableCollection of items. I've used UniformGrid, but the problem is is that I cannot make it to change the number of columns depending on the WindowSize. As an example, I have 10 items. the images have 100 pixels width. The window has 1000 px width. Technically, it should appear 10 items on a row. If I resize the window to, 500 px, i should have 2 rows of 5 images/row. If I grow it to 700 px, it should be one row of 4 images, and the second with 3 images. If I set the UniformGrid's Column, then it won't modify itself when I resize the window. I tried setting the listbox's HorizontalAlignment or VerticalAlignments to top/center/etc. ... So far, I have come to this:
<ListBox x:Name="ListBoxItems" ItemsSource="{Binding}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid x:Name="UniformGridTest" Columns="?"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<Image Name="ListItemImage" Source="{Binding LocImage.Source}"
RenderOptions.BitmapScalingMode="HighQuality"
MaxHeight="100" MaxWidth="100" Margin="0,0,5,0"
MouseDown="ListItemImage_MouseDown"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>`
I am using a ListBox because I need to have my items selectable. I hope i explained good enough for you to understand. Thank you very much! Adrian.
You should try WrapPanel
. It will fit so many item as your width allows, the rest will be moved to the next line. Eventually, it should look like what you need. But in this case you'll have some whitespace at the right on certain width values.
<ListBox x:Name="ListBoxItems" ItemsSource="{Binding}">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<WrapPanel x:Name="WrapPanel"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel >
<Image Name="ListItemImage" Source="{Binding LocImage.Source}" RenderOptions.BitmapScalingMode="HighQuality" MaxHeight="100" MaxWidth="100" Margin="0,0,5,0" MouseDown="ListItemImage_MouseDown"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>