Xamarin形成的网格布局尺寸不断减小

时间:2018-10-12 19:13:35

标签: layout xamarin.forms xamarin.ios xamarin.android grid

我们在Xamarin网格布局中遇到问题,其大小在OnAppearing方法中定义。每次我们调用OnAppearing方法时,网格的大小都会不断减小,而不会出现确切的问题

这是代码

  gridLayout.RowDefinitions.Add(new RowDefinition(){
            Height = new GridLength(5, GridUnitType.Star),
        });
        gridLayout.RowDefinitions.Add(new RowDefinition(){
            Height = new GridLength(5, GridUnitType.Star),
        });
        gridLayout.ColumnDefinitions.Add(new ColumnDefinition()
        {
            Width = new GridLength(2, GridUnitType.Star),
        });
        gridLayout.ColumnDefinitions.Add(new ColumnDefinition(){
            Width = new GridLength(2, GridUnitType.Star),
        });
        gridLayout.ColumnDefinitions.Add(new ColumnDefinition(){
            Width = new GridLength(2, GridUnitType.Star),
        });
        gridLayout.ColumnDefinitions.Add(new ColumnDefinition(){
            Width = new GridLength(2, GridUnitType.Star),
        });
        gridLayout.ColumnDefinitions.Add(new ColumnDefinition(){
            Width = new GridLength(2, GridUnitType.Star),
        });


        var productIndex = 0;
        for (int rowIndex = 0; rowIndex < 2; rowIndex++)
        {
            for (int columnIndex = 0; columnIndex < 5; columnIndex++)
            {
                if (productIndex >= CategoryArray.Count)
                {
                    break;
                }
                var category = CategoryArray[productIndex];
                productIndex += 1;
                var categoriesView = new CategoriesView
                {
                    BackgroundColor = Color.White
                };

                if(category.Image == null){
                    categoriesView.CategoriesImage.Source = "category_logo";
                }else{
                    categoriesView.CategoriesImage.Source = category.Image;
                }

                //categoriesView.BackgroundColor = Color.Olive;
                categoriesView.TextLabel.Text = category.Name;
                categoriesView.CategoryId = category.Id.ToString();
                gridLayout.Children.Add(categoriesView, columnIndex, rowIndex);

                //gridLayout.BackgroundColor = Color.Beige;
            }
        }

每次OnAppearing调用时,页面都会重新加载(这是功能),并且网格大小会不断减小。

1 个答案:

答案 0 :(得分:0)

您仅应在构造函数中(或在构造函数中调用的XAML中)声明一次Grid结构。每当调用OnAppearing时,您都将向现有Grid添加2个新行和5个新列,因此其大小会减小。

此外,通过查看添加了编写逻辑的元素,您可能应该将ListView与Grid ViewCell一起使用,并将ItemsSource设置为ObservableCollection,以便它可以自动更新