Can read my class inside the mouse click event but can't modify it, why?

I have some problem that i can only update my gui inside my Mainwindow() method. And cant really figure out why it does not work inside a event to change the gui. Im using bindings and a viewmodel class as well.

So it seems like my bindings stop to work when i go outside my mainwindow?

Any ideas what could be wrong?

Thanks!

public partial class MainWindow : Window
{


    public ObservableCollection<ChessPiece> ItemX { get; set; }

    public MainWindow()
    {
       ItemX = new ObservableCollection<Chess>();

       InitializeComponent();
       DataContext = ItemX ;
       ItemX.Add(new Chess() { PosX = 0, PosY = 0, Type_ = Piece.Farmer, Player_ = PiecePlayer.Black });
       ItemX.Add(new Chess() { PosX = 0, PosY = 1, Type_ = Piece.Farmer, Player_ = Player.Black });


  ItemX.ElementAt(1).PosX = 5; //This works perfect, my GUI changes! 
}      

 public void ChessBoardClick(object sender, MouseButtonEventArgs e)
    {
       ItemX.ElementAt(0).PosX = 3; //Wont work, but the values inside ItemX changes. 


    }
Jon Skeet
people
quotationmark

Currently your GUI doesn't change so much as start off right... you don't have a MainWindow method, you have a MainWindow constructor. The UI will only finish updating after that constructor has completed, by which time PosX will be 5 already.

To get your UI to react to property changes, your Chess class will need to implement INotifyPropertyChanged, so that an event will be fired when you change the PosX property.

As a side note, it would be more idiomatic to use the collection's indexer than the ElementAt method, e.g.

ItemX[0].PosX = 3;

people

See more on this question at Stackoverflow