Xamarin Forms: Grid button UI breaks when click restart button

自作多情 提交于 2021-02-05 11:48:40

问题


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:

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.


回答1:


you are adding new rows and cols to an existing Grid without clearing it first



来源:https://stackoverflow.com/questions/64151511/xamarin-forms-grid-button-ui-breaks-when-click-restart-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!