Based on the question How to associate an array of objects with elements in grid cells
Unlike the question specified in the link, I have a one-dimensional array of data that needs to be displayed in a strictly specified number of rows and columns (say 2 rows and 3 columns).
Here is an example:
There is a class that stores information about the image:
class ImageInfo { private string imgPath_; public Uri Uri { get { return new Uri(imgPath_, UriKind.Relative);} } public ImageInfo(string imgPath) { imgPath_ = imgPath; } } There is an array of these classes:
ImageInfo[] imgInfo_ = new ImageInfo[] { new ImageInfo("img/0.jpg"), new ImageInfo("img/1.jpg"), new ImageInfo("img/2.jpg"), new ImageInfo("img/3.jpg"), new ImageInfo("img/4.jpg"), new ImageInfo("img/5.jpg") }; There is a linear array to two-dimensional converter:
class ImgProvider : IEnumerable<IEnumerable<ImageInfo>> { readonly int ROW_COUNT = 2; readonly int COL_COUNT = 3; List<ImageInfo> _imgInfo; public ImgProvider(List<ImageInfo> imgInfo) { _imgInfo = imgInfo; } public IEnumerator<IEnumerable<ImageInfo>> GetEnumerator() { for (int i = 0; i < ROW_COUNT; i++) { yield return ColumnWraper(i); } } private IEnumerable<ImageInfo> ColumnWraper(int i) { for (int j = 0; j < COL_COUNT; j++) { int num = i == 0 ? j : j + COL_COUNT; yield return _imgInfo[num]; } } IEnumerator IEnumerable.GetEnumerator() => GetEnumerator(); } Markup displaying 2 rows of images using recursive ItemsControl :
<ItemsControl x:Name="IC" ItemsSource="{Binding}"> <ItemsControl.ItemTemplate> <DataTemplate> <ItemsControl ItemsSource="{Binding}"> <ItemsControl.ItemsPanel> <ItemsPanelTemplate> <StackPanel IsItemsHost="True" Orientation="Horizontal"/> </ItemsPanelTemplate> </ItemsControl.ItemsPanel> <ItemsControl.ItemTemplate> <DataTemplate> <Grid> <Button> <Button.Template> <ControlTemplate> <Image Source="{Binding Path=Uri}"/> </ControlTemplate> </Button.Template> </Button> </Grid> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> </DataTemplate> </ItemsControl.ItemTemplate> </ItemsControl> Installing DataContext :
IC.DataContext = new ImgProvider(imgInfo.ToList<ImageInfo>()); If we set the size of Width and Height (for example 100x100) of the Grid , in which the Button with the picture is embedded, we get the following form:
those. all pictures fit naturally
But if you remove the size from the Grid the pictures will stretch to their true size:
Question : how to make so that the pictures evenly stretched in full form? Those. would all 2 rows fit and when the size of the form changes, would the size of the pictures change too?
UPD: If you use UniformGrid Columns="3" , instead of StackPanel , as recommended in the answer given, the situation becomes better, but all the same the pictures do not fit completely:
If you look in Live Tree View, you will see the following situation:
In ItemsPresenter a ItemsPresenter embedded, which apparently stretches to the content.



