【问题标题】:Binding scope doesn't change inside collectionview/listview绑定范围在 collectionview/listview 内不会改变
【发布时间】:2023-03-22 23:35:01
【问题描述】:

我有一个造型师的 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}"/>

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

【问题讨论】:

  • 尝试删除x:DataType="viewmodels:WallViewModel"

标签: xaml xamarin.forms


【解决方案1】:

由于您将以下代码设置为用户模型,当您使用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- 绑定/编译绑定

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

删除x:DataType="viewmodels:WallViewModel 后,&lt;Label Text="{Binding Name}"/&gt; 应该可以工作了。

【讨论】:

    【解决方案2】:

    只需将迭代类型放入 DataTemplate 中即可:

    <DataTemplate x:DataType="viewmodels:xxx">
    ...
    </DataTemplate>
    

    【讨论】:

      猜你喜欢
      • 2016-12-12
      • 2012-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-20
      • 1970-01-01
      • 2017-08-05
      • 1970-01-01
      相关资源
      最近更新 更多