【问题标题】:Xamarin Collectionview Binding Not workingXamarin Collectionview 绑定不起作用
【发布时间】:2020-08-13 14:02:09
【问题描述】:

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

【问题讨论】:

  • 如果 ListView 工作,它可能不是绑定问题。布局引擎更有可能无法确定您的布局需要多大的尺寸。您可以通过在 Label 中硬编码一个值来轻松测试它以查看它是否显示。
  • 在视图中使用数据库模型不是一个好主意。
  • 是的,我根据您在另一个线程上的评论做到了。我希望看到它打印 HC 值乘以计数,但没有显示。
  • @neil 新文档推荐它。现在是选项卡式项目中新项目附带的代码
  • 哪个文档推荐它?这不应该是 MVVM,而不是 DBVVM。如果您更新 Category.Name,您的视图将不会更新,因为您的数据库类不支持 INotifyPropertyChanged。

标签: c# user-interface xamarin.forms observablecollection


【解决方案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>

【讨论】:

  • Jasmin,我还是什么都没有
  • 我可以看看你的 XAML 吗?
  • 是的,我已经在我的回答中添加了请检查。
  • 是的,它有效。我的原始代码也可以,但是我使用的临时电话处于黑暗模式,所以我什么都看不到。
猜你喜欢
  • 1970-01-01
  • 2020-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多