title: Binding 2d array to a Grid
body: <p>I'm trying to make a little game in C# using WPF. In one of my Modelclasses I have a Map, which is a 2D-array filled with Enumeration objects. Each of these objects represents a type of tile.</p>
  
  <p>In my View these Tiles need to be converted to an Image and the image needs to be set to the right coordinates in the Grid.</p>
  
  <p>How do I bind the array to the Grid or the Images in the view so that it will auto-update when the array changes?</p>
  
  <p>This how it works now:</p>
  
  <p><em>Enumeration that's used to fill the array:</em></p>
  
  <pre><code>public enum Tile { FLOOR, WALL, DESTINATION, EMPTY }
  </code></pre>
  
  <p><em>Method to create and position all the Images (this is in the code-behind):</em></p>
  
  <pre><code>public void LoadMap(Map mapModel)
          {            
              Tile[,] tiles = mapModel.TileMap;
  
              int nRows = tiles.GetLength(1);
              int nCols = tiles.GetLength(0);
  
              for (int i = 0; i &lt; nCols; i++)
              {
                  ColumnDefinition col = new ColumnDefinition();               
                  map.ColumnDefinitions.Add(col);
              }
  
              for (int i = 0; i &lt; nRows; i++)
              {
                  RowDefinition row = new RowDefinition();                
                  map.RowDefinitions.Add(row);
              }            
  
              for (int y = 0; y &lt; nCols; y++)
              {
                  for (int x = 0; x &lt; nRows; x++)
                  {
                      Image img = new Image();
                      switch (tiles[y, x])
                      {
                          case Tile.FLOOR:
                              img.Source = _srcFloor;
                              break;
  
                          case Tile.WALL:
                              img.Source = _srcWall;
                              break;
  
                          case Tile.DESTINATION:
                              img.Source = _srcDestination;
                              break;
  
                          case Tile.EMPTY:
                              img.Source = _srcEmpty;
                              break;
                      }
  
                      img.SetValue(Grid.ColumnProperty, x);
                      img.SetValue(Grid.RowProperty, y);                                       
  
                      map.Children.Add(img);                    
                  }
              }
          }
  </code></pre>
  
  <p><em>XAML:</em></p>
  
  <pre><code>&lt;Grid Name="map"&gt;
  
  &lt;/Grid&gt;
  </code></pre>
  
  <p><em>And here is a screenshot of how it looks:</em>
  <img src="https://i.stack.imgur.com/FxrLZ.png" alt="sokoban screenshot"></p>