Xamarin Collectionview绑定不起作用

问题描述

我在使用collectionview时遇到问题,我试图使绑定正常工作。 正如我在其他文章中所看到的,我试图通过设置涉及到的每个元素的最小高度和高度要求来设置高度,但是没有成功。我有一个带文本单元格的listview,这是我可以使它起作用的唯一方法

型号

    [Table("Category")]
    public class Category
    {
        [PrimaryKey,AutoIncrement]
        public int Id { get; set; }
        public string Name { get; set; }
    }

viewmodel

    public class Categoriesviewmodel : Baseviewmodel
    {
        public ObservableCollection<Category> Categories { get; }
        public Command LoadCategoriesCommand { get; }
        public Command AddCategoryCommand { get; }

        public Categoriesviewmodel()
        {
            Title = "Categories";
            Categories = new ObservableCollection<Category>();
            LoadCategoriesCommand = new Command(async () => await ExecuteLoadCategoriesCommand());

            AddCategoryCommand = new Command(OnAddCategory);
        }

        async Task ExecuteLoadCategoriesCommand()
        {
            IsBusy = true;

            try
            {
                Categories.Clear();
                var categories = await DataStore.GetCategoriesAsync();
                foreach (var cat in categories)
                {
                    Categories.Add(cat);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                IsBusy = false;
            }
        }

        public void OnAppearing()
        {
            IsBusy = true;
        }

查看

             xmlns:local="clr-namespace:FreeScanner.viewmodels"
             xmlns:model="clr-namespace:FreeScanner.Models"
             x:Name="browseCategoriesPage">

    <ContentPage.toolbaritems>
        <ToolbarItem Text="Add" Command="{Binding AddCategoryCommand}" />
    </ContentPage.toolbaritems>
    <RefreshView x:DataType="local:Categoriesviewmodel" Command="{Binding LoadCategoriesCommand}"
                 IsRefreshing="{Binding IsBusy,Mode=TwoWay}">
        <CollectionView x:Name="CategoriesListView"
                        ItemsSource="{Binding Categories}">
            <CollectionView.ItemTemplate>
                <DataTemplate>
                    <Grid Padding="10" x:DataType="model:Category">
                        <Grid.RowDeFinitions>
                            <RowDeFinition Height="Auto" />
                            <RowDeFinition Height="Auto" />
                        </Grid.RowDeFinitions>
                        <Grid.ColumnDeFinitions>
                            <ColumnDeFinition Width="Auto" />
                            <ColumnDeFinition Width="Auto" />
                        </Grid.ColumnDeFinitions>
                        <Label Grid.Column="1"
                               Grid.Row="1"
                               Text="{Binding Name}"
                               FontAttributes="Bold" />
                    </Grid>
                </DataTemplate>
            </CollectionView.ItemTemplate>  
        </CollectionView>
        <!--<ListView ItemsSource="{Binding Categories}" 
                  x:Name="CategoriesListView"
                  SelectionMode="None"
                  RowHeight="50">
            <ListView.ItemTemplate>
                <DataTemplate x:DataType="model:Category">
                    <TextCell Text="{Binding Name}"/>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>-->
    </RefreshView>

当我调试并悬停在CollectView ItemSource类别上时,确实看到Count = 1,并且可以验证是否已从数据库正确加载。

Screenshot of Page

解决方法

=>尝试一下,效果很好

public class CategoriesViewModel : BaseViewModel
    {
        public ObservableCollection<Category> Categories { get; set; } = new ObservableCollection<Category>();
        public Command LoadCategoriesCommand { get; }
        public Command AddCategoryCommand { get; }

        public CategoriesViewModel()
        {
            Title = "Categories";
            
            LoadCategoriesCommand = new Command(async () => await ExecuteLoadCategoriesCommand());

            AddCategoryCommand = new Command(OnAddCategory);
        }

        async Task ExecuteLoadCategoriesCommand()
        {
            IsBusy = true;

            try
            {
                Categories.Clear();
                var categories = await DataStore.GetCategoriesAsync();
                foreach (var cat in categories)
                {
                    Categories.Add(new Category{Name=cat.Name});
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                Debug.WriteLine(ex.Message);
            }
            finally
            {
                IsBusy = false;
            }
        }

        public void OnAppearing()
        {
            IsBusy = true;
        }

=>这是我的Xaml

<CollectionView x:Name="CourseList"  IsVisible="{Binding IsVisibleCourse}" ItemsSource="{Binding Courses}"  >
                <CollectionView.ItemsLayout>
                    <GridItemsLayout  Orientation="Vertical" Span="2"/>
                </CollectionView.ItemsLayout>
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <StackLayout Padding="5" Spacing="-6">
                            <Frame BorderColor="LightGray" HeightRequest="{OnIdiom Phone=140,Tablet=210}" CornerRadius="10" HasShadow="False" Padding="5">
                                <StackLayout Padding="5" Orientation="Vertical" Spacing="5">
                                    
                                    <ffimageloading:CachedImage x:Name="Pic" LoadingDelay="0"
                                                                            Margin="0,5,0" WidthRequest="{OnIdiom Phone=60,Tablet=100}"
                                                                   HeightRequest="{OnIdiom Phone=60,Tablet=100}" Source="{Binding ImageURL}"
                                                                    HorizontalOptions="CenterAndExpand" VerticalOptions="Center"
                                                                        BackgroundColor="Transparent" Aspect="Fill" >
                                        <ffimageloading:CachedImage.Transformations>
                                            <ffTransformations:CircleTransformation />
                                        </ffimageloading:CachedImage.Transformations>
                                       
                                    </ffimageloading:CachedImage>

                                    <Label Text="{Binding Name}" MaxLines="2" Style="{StaticResource TextDefaultStyle}" TextColor="Black" HorizontalTextAlignment="Center" VerticalOptions="Fill"/>
                                    <Label Text="{Binding Description}" MaxLines="2" Style="{StaticResource TextMicroStyle}" HorizontalTextAlignment="Center" VerticalOptions="Fill" FontAttributes="Bold"/>
                                   
                                </StackLayout>
                                <Frame.GestureRecognizers>
                                    <TapGestureRecognizer NumberOfTapsRequired="1"
                                                Command="{Binding Path=BindingContext.CourseListCommand,Source={x:Reference CourseList}}" CommandParameter="{Binding .}"/>
                                </Frame.GestureRecognizers>
                            </Frame>
                        </StackLayout>
                       
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>