Xamarin Collectionview 绑定不工作

Xamarin Collectionview Binding Not working

我在使用 collectionview 时遇到问题,我正在尝试让绑定正常工作。 正如我在其他帖子中看到的那样,我试图通过设置涉及的每个元素的 miniumheight 和 heightrequest 来设置高度,但没有成功。我有一个带有文本单元格的列表视图,这是我让它工作的唯一方法。

型号

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

视图模型

    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,并且我可以验证它是否从数据库中正确加载。

=>试试这个效果很好

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,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>