【问题标题】:Why can't I use properties from my ObservableCollection inside a ListView为什么我不能在 ListView 中使用 ObservableCollection 中的属性
【发布时间】:2022-01-16 18:57:24
【问题描述】:

我正在尝试返回Observablecollection,这似乎很好。当我想获取集合中每个项目的属性时,我收到错误“Binding: Property '' not found on”。

我有以下代码:
我删除了所有标记代码,以便于阅读

查看

<ListView ItemsSource="{Binding Books}">
    <ListView.ItemTemplate>
        <DataTemplate>
            <ViewCell>
                <Grid>
                    <Label Text="{Binding Title}" />
                    <Label Text="{Binding Description}" />
                    <Label Text="{Binding Date}" />
                </Grid>
            </ViewCell>
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

视图模型

public class BookListPageViewModel : ViewModelBase
{
    private ObservableCollection<Book> _books = new();
    public ObservableCollection<Book> Books
    {
        get => _books;
        set => SetProperty(ref _books, value);
    }
}

型号

public class Book : ModelBase
{
    public string Title { get; set; }
    public string Description { get; set; }
    public string Date { get; set; }
}

奇怪的是,早先我在ViewModel 文件中有类Book 并且确实有效。但我希望这个类位于Models 文件夹中。
这就是我的ViewModel 以前的样子。

namespace Some.Namespace.Project
{
    public class Book : ModelBase
    {
        public string Title { get; set; }
        public string Description { get; set; }
        public string Date { get; set; }
    }

    public class BooksListPageViewModel : ViewModelBase
    {
        private ObservableCollection<Book> _books = new();
        public ObservableCollection<Book> Books
        {
            get => _books;
            set => SetProperty(ref _books, value);
        }
    }
}

怎么找不到Bindings (Title, Description, and Date)

【问题讨论】:

  • 这里有点胡思乱想,但是您使用List 作为绑定到 ItemSource 的属性的名称这一事实可能会让人失望(有一个System.Collections.Generic.List)。您可以尝试重命名为更具体的名称,例如ListOfParts
  • 啊,是的。也许不是这里的最佳选择,但这并不是我代码中的变量名。我不允许分享任何代码。我编辑了变量名:)
  • 为什么private ObservableCollection&lt;Book&gt; _bookspublic ObservableCollection&lt;Parts&gt; Books 是不同的类型?这看起来很奇怪,但也许这只是一个错字。我还认为SetProperty 引发了属性更改事件?

标签: c# xaml xamarin.forms


【解决方案1】:

我是 XAML 的新手,显然可以在 ContentPage 中添加您自己的 x-tags

所以在我的 ContentPage 中,我添加了 xmlns:models="clr-namespace:Namespace.To.Models"
有了这个标签,我可以将我的DataTemplate 更改为&lt;DataTemplate x:DataType="models:Book"&gt;

这解决了我的问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-20
    • 1970-01-01
    • 2016-09-20
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 2012-10-29
    相关资源
    最近更新 更多