public MainWindow() { _LightGrid = new LightGrid(Columns, Rows); _Buttons = new Button[Rows, Columns]; InitializeComponent(); // Set the grid size so the lights rendering in the correct order grid.Columns = Columns; grid.Rows = Rows; // Loops the lights and attach click handlers foreach (var light in _LightGrid.Lights) { var button = new Button() { Background = Brushes.Gray }; // Apply the event handler and add the light to the grid button.Click += new RoutedEventHandler((object sender, RoutedEventArgs e) => { if (_LightGrid.Complete) { return; } _LightGrid.ToggleLight(light.X, light.Y); RedrawGrid(); if (_LightGrid.Complete) { MessageBox.Show("You win"); } }); _Buttons[light.Y, light.X] = button; grid.Children.Add(button); } // Reset and randomize the grid _LightGrid.ResetAndRandomizeStates(); RedrawGrid(); }