Home > front end >  WPF binding to 2D array
WPF binding to 2D array

Time:07-06

I've been learning WPF and MVVM. I am trying to create a chess game. I have the game state represented as a 2D (8x8) array of pieces. The board is displayed as a UniformGrid of 64 elements. Everytime the game state changes, I loop through the game state array and update each square on the displayed board accordingly. Is there a better (more WPF) way to do this? I thought I could somehow bind each of the squares of the displayed board to the game state and define a value convertor that would access the array but I don't really know how to do that. I would appreciate any help.

CodePudding user response:

Maybe switch to using ObservableCollection and bind it with, say a ListBox's ItemsSource property. also Consider extending the collection class to support 2d indexer so that you can manipulate cells the same way you did with the 2d array:

public class ObservableCollectionC<T> : ObservableCollection<T>{
    public ObservableCollectionC(IEnumerable<T> p) : base(p){ }
    public T this[int m, int n]{
        get  { return this[m*8 n]; }
        set  { this[m*8 n] = value; }
    }
}
  • Related