Xamarin ListView不在XAML上填充。绑定问题

时间:2018-12-26 06:52:36

标签: c# listview xamarin xamarin.forms

我正在遵循MSDN中的这个基本示例,但是似乎有些错误。运行程序时出现此错误

错误消息:

Binding: 'Title' property not found on 'HelloWorld.MainPage+Post', target property: 'Xamarin.Forms.TextCell.Text'

我在某处找到了一篇有关设置 BindingContext 的文章,但这并没有解决任何问题。任何指导将不胜感激。

XAML代码:

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
         xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
         xmlns:local="clr-namespace:HelloWorld"
         x:Class="HelloWorld.MainPage">

<ListView x:Name="rssList">
    <ListView.ItemTemplate>
        <DataTemplate>
            <TextCell Text="{Binding Title}" />
        </DataTemplate>
    </ListView.ItemTemplate>
</ListView>

MainPage.xaml.cs代码

 using System;
  using System.Collections.Generic;
 using System.Collections.ObjectModel;
 using System.Linq;
 using System.Text;
 using System.Threading.Tasks;
using System.Xml.Linq;
using Xamarin.Forms;

namespace HelloWorld
{
    public partial class MainPage : ContentPage
    {
        ObservableCollection<Post> posts = new ObservableCollection<Post>();
        public MainPage()
        {
            InitializeComponent();

            var posts = new 
    RssFeedReader().ReadFeed(@"http://www.espn.com/espn/rss/news");
            Console.WriteLine(posts.ToList().Count);
            Console.ReadLine();

            rssList.ItemsSource = posts;

            BindingContext = this;
        }
public class RssFeedReader
        {
            public string Title { get; set; }
            public ObservableCollection<Post> ReadFeed(string url)
            {
                var rssFeed = XDocument.Load(url);

                var rssPost = from item in rssFeed.Descendants("item")
                            select new Post
                            {
                                Title = item.Element("title").Value,
                                Description = item.Element("description").Value,
                                PublishedDate = item.Element("pubDate").Value
                            };
                var myObservableCollection = new ObservableCollection<Post>(rssPost);
                return myObservableCollection;
            }
        }
  public class Post
        {
            public string PublishedDate;
            public string Description;
            public string Title;
        }

    }
}

1 个答案:

答案 0 :(得分:1)

为了将DataBindingPost类一起使用,它应该具有properties。因此,至少标题应如下所示:

public string Title { get; set; }

P.S .:不需要将BindingContext设置为self,因为您直接设置了ItemSource,而没有涉及数据绑定引擎。