I have a grid built using Grid 10 * 10. In the cells of this grid are Button elements created and placed there dynamically.

The question is how do I turn to these cells so that I can interact with the elements placed in them (for example, change their color, or the content property). I can not understand how this is done in WPF ..

Method to create a button.

 private void CreateItemField(int i, int j, Brush color) { Button button = new Button(); button.Margin = new Thickness(0.5d); button.Background = color; button.Name = "btn" + i + j; MainGrid.Children.Add(button); Grid.SetColumn(button, i); Grid.SetRow(button, j); } 

    1 answer 1

    In a simple way - no way.

    If for some reason you decided to create content in the code-behind (why not through ItemsControl , with MVVM?), The easiest way to create is to remember the display of the cell number in the button.

    If you don't, the Grid itself has no clue about the cells. You can poll Children for it, get a list of all children, and search among them in a loop (or via LINQ), using the Grid.GetRow and Grid.GetColumn to get the necessary indices.


    Here is the code for you:

     Button[,] buttons = new Button[10, 10]; 
     private void CreateItemField(int i, int j, Brush color) { Button button = new Button(); button.Margin = new Thickness(0.5d); button.Background = color; button.Name = "btn" + i + j; MainGrid.Children.Add(button); Grid.SetColumn(button, i); Grid.SetRow(button, j); buttons[i, j] = button; } 
    • I am new to WPF and therefore ask. - Roman Timokhov
    • By the way, when I created it, I did it — I wrote down a cell label in the button name. How now for her to get it? Updated the question with an example of creating a button. - Roman Timokhov
    • @RomanTimohov: Again, no way, just a brute force. Grid does not display items by name. Well, or have a dictionary on the code-behind side. - VladD
    • @ RomanTimokhov: Look here , is this your case? - VladD
    • Thanks, I will understand. - Roman Timokhov