There is an array of figures, there is a cycle in which the color of a certain figure on a form should change. But the loop only changes color in the array. How to implement the connection between the array and Childrens grid?

//массив фигур private Rectangle[,] rField; //Участок кода заполнения массива rField = new Rectangle[HeigthSize, WidthSize]; for (int i = 0; i < HeigthSize; i++) { for (int j = 0; j < WidthSize; j++) { rField[i, j] = new Rectangle(); Grid.SetColumn(rField[i, j], j); Grid.SetRow(rField[i, j], i); rField[i, j].MouseDown += this.rctnField_MouseDown; rField[i, j].Stroke = Brushes.Cyan; rField[i, j].StrokeThickness = 0.5; rField[i, j].Fill = Brushes.White; GameGridField.Children.Add(rField[i, j]); } } //Участок кода в котором должен меняться цвет фигуры while(true) { System.Threading.Thread.Sleep(1000); if (rField[1, 1].Fill == Brushes.Black) rField[1, 1].Fill = Brushes.White; else rField[1, 1].Fill = Brushes.Black; } 

ps I make the game Life, I do not keep the whole field but only the living cells, so I am looking for ways to realize the field. Maybe there are some more effective methods, I will be glad to read.

  • First, no Thread.Sleep , you hang up the interface. Secondly, why not MVVM? - VladD
  • Not MVVM because I don't know it yet, and I have no idea how to implement it. This is actually my first standalone application on WPF. With Thread.Sleep understood, remove. - Vlad Hlushkov
  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

1 answer 1

I think everything changes as it should. Just because of Sleep you don’t see any changes, because the UI thread is blocked by an infinite loop. Try this code:

 async Task ChangeColorPeriodically() { while(true) { await Task.Delay(1000); // <-- if (rField[1, 1].Fill == Brushes.Black) rField[1, 1].Fill = Brushes.White; else rField[1, 1].Fill = Brushes.Black; } }