2

I am making a chess application in wpf. I am currently creating the UI. This is my first time using WPF and i am a little confused how to bind the 2D array to a suitable xaml container in a simple manner.

For example, this is the code for the UI:

public partial class GameView : Window
{
    private Game game;
    private const int tableSize = 8;
    ChessCell[,] chessMatrix = new ChessCell[tableSize, tableSize];
    public GameView(bool loadGame)
    {
        InitializeComponent();        
        game = new Game(loadGame);
        GenerateEmptyGrid();
    }

    private void GenerateEmptyGrid()
    {   
        for (int i = 0; i < tableSize; i++)
        {               
            for (int j = 0; j < tableSize; j++)
            {
                chessMatrix[i, j] = new ChessCell();
                if ((j + i) % 2 == 0)
                {
                    chessMatrix[i, j]._tileColor = Color.FromRgb(255, 255, 255);
                }
                else
                {
                    chessMatrix[i, j]._tileColor = Color.FromRgb(0, 0, 0);
                }
            }
        }

        chessGrid.ItemsSource = chessMatrix;
    }

    public class ChessCell
    {
        public string _piece { get; set; }
        public Color _tileColor { get; set; }
    }
}

This generated the error: System.ArgumentException: 'Array was not a one-dimensional array.'

On the line: chessGrid.ItemsSource = chessMatrix;

Chess grid is a datagrid:

chessGrid:

  <Grid>
        <DataGrid Name ="chessGrid" SelectionMode="Single" SelectionUnit="Cell">

        </DataGrid>
 </Grid>

So obviously it accepts only a 1D array. I have looked some but i cant seem to find a xaml container that you can easily bind a 2D array too? Any suggestions on such a container or are there any other simple way to view a 2D array?

Tagor
  • 937
  • 10
  • 30

1 Answers1

1

What I would do is have a StackPanel (with orientation being vertical), with each item in this panel containing another StackPanel (orientation horizontal). That would mean your ViewModel has to contain an array of arrays, instead of a matrix.

This means you will need to have a conversion between your Model and your VM (I strongly recommend you use the MVVM architectural pattern, if you are working with WPF).

Florin Toader
  • 337
  • 1
  • 9