首页 > 解决方案 > 绑定范围在 collectionview/listview 内不会改变

问题描述

我有一个造型师的 ObservableCollection,我想使用 CollectionView 在我的视图中显示

这是collectionview的代码

<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml" 
             xmlns:viewmodels="clr-namespace:Appointments.ViewModels" 
             x:DataType="viewmodels:WallViewModel"
             x:Class="Appointments.Views.WallPage">


    <ContentPage.BindingContext>
        <viewmodels:WallViewModel/>
    </ContentPage.BindingContext>

    <ContentPage.Content>
        <StackLayout>
            <FlexLayout 
                JustifyContent="SpaceBetween"
                Margin="10, 20">

                <Entry 
                    WidthRequest="250"
                    Placeholder="search.."/>
                <Button 
                    Text="Filters"
                    Command="{Binding OpenFilterCommand}"
                    />
            </FlexLayout>

            <CollectionView 
                x:Name="StylistList"
                BackgroundColor="Transparent"
                ItemsSource="{Binding Stylists}">
                <CollectionView.ItemTemplate>
                    <DataTemplate>
                        <Label Text="{Binding Name}"/>
                    </DataTemplate>
                </CollectionView.ItemTemplate>
            </CollectionView>
        </StackLayout>
    </ContentPage.Content>
</ContentPage>

造型师模型继承自具有公共属性“名称”的用户模型

        public string Name { get; set; }

但是如果我运行这段代码,它会抛出一个错误说

“绑定:在 WallViewModel 上找不到属性“名称””

但是如果我更改该标签以绑定到

<Label Text="{Binding .}"/>

在应用程序运行时,我将其改回

<Label Text="{Binding Name}"/>

它会正常工作并显示集合中的所有名称

标签: xamlxamarin.forms

解决方案


由于您将下面的代码设置为 User 模型,当您使用时x:DataType="viewmodels:WallViewModel"会抛出错误Property "Name" not found on "App8.WallViewModel".

  public string Name { get; set; }

如果更改使用 x:DataType,则需要使用包含 Name 属性的类。

有关 x:DataType 的更多详细信息,请查看 MS 文档。 https://docs.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/data-binding/compiled-bindings _

正如杰森所说,删除x:DataType="viewmodels:WallViewModel"将修复此错误。

删除后x:DataType="viewmodels:WallViewModel<Label Text="{Binding Name}"/>应该可以工作。


推荐阅读