Search code examples
c#wpfxamlchess

C# WPF Chess binding and ObservableCollection, how to modify?


so i'm doing a chess game just to learn c# and WPF.

Have been googling around alot and have so far came up with some code, my problem now is that when i create chess pieces on my board i dont know how to modify them inside the observbleCollection, for example removing one piece. With this code i can add the pieces to the board.

But how can i modify it after i have created it?

this.ChessBoardd.ItemsSource = new ObservableCollection<ChessPiece>
{
    new ChessPiece{Type_ = Piece.Pawn, Player_ = PiecePlayer.Black, Posx_ = 30, Posy_ = 50},
    new ChessPiece{Type_ = Piece.Pawn, Player_ = PiecePlayer.Black, Posx_ = 30, Posy_ = 50} 
};

In the same file i have the following code:

public class ChessPiece : INotifyPropertyChanging
{
    private int posx_;
    private int posy_;       

    public int Posx_
    {
        get { return this.posx_; }
        set { this.posx_ = value; OnPropertyChanged("Posx_"); }            
    }

    public int Posy_
    {
        get { return this.posy_; }
        set { this.posy_ = value; OnPropertyChanged("Posy_"); } 
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null) handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

Here from my idea was that i could some how change my observablecollection array for example (this doesn't work since i dont know how to do it) and then the ui would update the board automatlicy since i have the infotifyproperychangin and binding in the xaml file,

this.ChessBoardd.IteamsSource[0].Posx_ = 50; 

Any ideas on this? Should i approch from a diffrent way?


Solution

  • You can use the Item method of the ObservableCollection class.

    So the right way to implement this

    this.ChessBoardd.IteamsSource[0].Posx_ = 50;
    

    is:

    this.ChessBoardd.IteamsSource.Item(0).Posx_ = 50;
    

    Also on your properties it's a nice optimization if you check

    set
    {
         if(value!=posy)
         {
             posy = value
             PropertyChanged("PosY");
         }
     }
    

    Oh and use INotifyPropertyChanged instead of INotifyPropertyChanging