C#WPF国际象棋绑定和ObservableCollection,如何修改

本文关键字:何修改 修改 国际象棋 绑定 ObservableCollection C#WPF | 更新日期: 2023-09-27 18:29:51

所以我下象棋只是为了学习c#和WPF。

我已经在谷歌上搜索了很多次,到目前为止已经想出了一些代码,我现在的问题是,当我在棋盘上创建棋子时,我不知道如何在observableCollection中修改它们,例如删除一个棋子。有了这个代码,我可以把这些碎片添加到棋盘上。

但是在我创建了它之后,我该如何修改它呢?

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} 
};

在同一个文件中,我有以下代码:

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));
    }
}

例如,我的想法是,我可以改变我的observalecollection数组(这不起作用,因为我不知道如何做),然后ui会自动更新板,因为我在xaml文件中有适当的信息更改和绑定

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

对此有什么想法吗?我应该从不同的方式接近吗?

C#WPF国际象棋绑定和ObservableCollection,如何修改

您可以使用ObservableCollection类的Item方法。

因此,实现的正确方法

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

是:

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

同样在你的属性上,如果你检查,这是一个很好的优化

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

哦,使用INotifyPropertyChanged而不是INotifyProperty更改