0

I found lots of tutorials on how to add things to a grid manually in the XAML file, but the grid I am making is a 15x15 monster that needs to have over 100 images inserted into it. I was hoping there was some accessor that would allow me to add an image to it in the code-behind file using a loop.

<Grid Name="ScrabbleBoard">
    <Grid.ColumnDefinitions>
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
        <ColumnDefinition />
    </Grid.ColumnDefinitions>
    <Grid.RowDefinitions>
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
        <RowDefinition />
    </Grid.RowDefinitions>
</Grid>
user3796261
  • 751
  • 5
  • 10
  • I would suggest you to create a user control with an image, and inside your for loop place the image inside a canvas. – Sajeetharan Jul 15 '14 at 04:20
  • yes but how do I add that to the grid. I can do that manually, but I can't figure out what the code for it is in the code-behind. – user3796261 Jul 15 '14 at 04:21
  • Pls check this out: http://stackoverflow.com/questions/7938779/image-column-in-wpf-datagrid – c_str Jul 15 '14 at 04:51

2 Answers2

1

You need to use Grid::Children property to add the image element. Then set element's row and column using Grid.SetRow(element, rowIndex) / element.SetValue(Grid.RowProperty, rowIndex) and Grid.SetColumn(element, columnIndex) / element.SetValue(Grid.ColumnProperty, columnIndex)

for (int rowIndex = 0; rowIndex < ScrabbleBoard.RowDefinitions.Count; rowIndex++)
{
    for (int columnIndex = 0; columnIndex < ScrabbleBoard.ColumnDefinitions.Count; columnIndex++)
    {
        var imageSource = new BitmapImage(new Uri("pack://application:,,,/YourProjectName;component/YourImagesFolderName/YourImageName.jpg"));
        var image = new Image { Source = imageSource };
        Grid.SetRow(image, rowIndex);
        Grid.SetColumn(image, columnIndex);
        ScrabbleBoard.Children.Add(image);
    }
}
Yuliam Chandra
  • 14,494
  • 12
  • 52
  • 67
0

Since your not spanning or controlling width/height, it would be simpler to use a uniform grid control. That adds children to the next cell so can be done with a foreach loop over your image collection.

kidshaw
  • 3,423
  • 2
  • 16
  • 28