0

I am creating WPF application with ModernUI interface. Its a kind of photo gallery. Images are stored in some folder and are retrieved according to appropriate record in database. So my ViewModel gets information from database and binds "URI" column to Source property of Image.

What I need to do is to position these images to a view like in grid. Width and height of images is constant. Challenge here is that before runtime I do not know how many elements I have, so Grid should be created dynamically. I would be better if number of columns will be automatically counted depending on width of grid. For example, image width is 200, right margin is 50, so if grid (or parent element, never mind) width is 800, so we have 3 columns. But I can set number of columns explicitly; The most important thing is to position images so that it will look like a grid.

ViewModel returns ObservableCollection of elements (could be change to any necessary structure). I really appreciate XAML code with templates defined.

AskhatOmarov
  • 39
  • 2
  • 7

2 Answers2

2

Maybe you could try to set the grid.column and grid.row property dynamically. Check the possible width and height of your grid to specify the amount of pictures you can place in. Then define the rows and columns of your grid and add the image.

         for(amount of images) // define rows and colums
         {
            ColumnDefinition colDef = new ColumnDefinition();
            colDef.Width = new GridLength(specifiedwidth);
            yourgrid.ColumnDefinitions.Add(colDef);

            RowDefinition rowDef = new RowDefinition();
            rowDef.Height = new GridLength(specifiedheight);
            yourgrid.RowDefinition.Add(rowDef);
         }

         for(amount of images) // add your images to the grid
         {
            yourgrid.Children.Add(yourimage);

            Grid.SetColumn(yourimage, index); //set column index
            Grid.SetRow(yourimage, index); // set row index
         }
aDoubleSo
  • 1,128
  • 9
  • 19
1

You can just display them in a ListBox that has an ItemsPanelTemplate of type WrapPanel:

<ListBox ItemsSource="{Binding ImageUrls}">
    <ListBox.ItemsPanel>
        <ItemsPanelTemplate>
            <WrapPanel />
        </ItemsPanelTemplate>
    </ListBox.ItemsPanel>
    <ListBox.ItemTemplate>
        <Image Source="{Binding}" Stretch="None" />
    </ListBox.ItemTemplate>
</ListBox>

This should add the Image controls horizontally until there is no more room and then it will wrap them onto the next line and so on. If the Image sizes are constant as you say, then this should give you the look that you are after. Of course, you'll need to have your Image sources in the correct format in the collection.

Sheridan
  • 68,826
  • 24
  • 143
  • 183