locked
Xamarin Forms: Grid button UI breaks when click restart button RRS feed

  • Question

  • User351573 posted

    I am using a button inside the grid for showing letters to implement a Word search game. Initially, the UI is looking good, but when clicks the play again button the UI breaks.

    Screenshot:

    enter image description here

    Code for the setting button inside grid:

    void SetGridLayout(char[,] matrixToPrint)
    {
        int numRows = matrixToPrint.GetLength(0);
        int numCols = matrixToPrint.GetLength(1);
    
        gridLayout.HorizontalOptions = LayoutOptions.FillAndExpand;
        gridLayout.SetBinding(Button.HeightRequestProperty, new Binding("Width", source: gridLayout));
    
        for (int row = 0; row < numRows; row++)
        {
            gridLayout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
        }
        for (int col = 0; col < numCols; col++)
        {
            gridLayout.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
        }
    
        for (int rowIndex = 0; rowIndex < numRows; rowIndex++)
        {
            for (int columnIndex = 0; columnIndex < numCols; columnIndex++)
            {
                var Rowbutton = new Button
                {
                    Text = Char.ToString(matrixToPrint[rowIndex, columnIndex]),
                    VerticalOptions = LayoutOptions.FillAndExpand,
                    HorizontalOptions = LayoutOptions.FillAndExpand,
                    Padding = 0,
                    Margin = 0,
                    BackgroundColor = Color.White
                };
                Rowbutton.SetBinding(Button.CommandProperty, "ClickCommand");
                Rowbutton.SetValue(Button.CommandParameterProperty, new PassObject(Rowbutton, rowIndex.ToString() + "," + columnIndex.ToString()));
                Rowbutton.SetBinding(Button.HeightRequestProperty, new Binding("Width", source: Rowbutton));
                gridLayout.Children.Add(Rowbutton, columnIndex, rowIndex);
            }
        }
    }
    

    I tried a lot to find the cause behind this issue, but no luck. I have uploaded a sample project here for the reference. Thanks in advance.

    Thursday, October 1, 2020 8:19 AM

Answers

  • User351573 posted

    I am adding new rows and cols to an existing Grid without clearing it first. Adding the below code before adding a new row and column solved my problem.

    gridLayout.RowDefinitions.Clear();
    gridLayout.ColumnDefinitions.Clear();
    
    • Marked as answer by Anonymous Thursday, June 3, 2021 12:00 AM
    Thursday, October 1, 2020 11:26 AM