Xamarin Forms中ListView出现"sequence contains no elements"错误

8

我正在尝试从数据中填充ListView。 在我的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"
             x:Class="FormDemos.Views.Feedback">
    <ContentPage.Content>
        <Label>I am Testimonials Page</Label>

        <ListView x:Name="FeedbackList" />

    </ContentPage.Content>
</ContentPage>

在 CS 文件中
namespace FormDemos.Views
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class Feedback : ContentPage
    {
        class City
        {
            public string Name
            {
                get;
                set;
            }

            public string State
            {
                get;
                set;
            }
        }

        public Feedback()
        {
            InitializeComponent();
            var cities = new List<City>() {
                new City() {State = "FL", Name = "Miami"},
                new City() {State = "CA", Name = "San Francisco"},
                new City() {State = "CA", Name = "Los Angeles"},
                new City() {State = "FL", Name = "Orlando"},
                new City() {State = "TX", Name = "Houston"},
                new City() {State = "NY", Name = "New York City"},
            };
            FeedbackList.ItemsSource = cities;
        }
    }
}

每次我构建这个项目时,都会出现“序列中不包含元素”的错误。我看到一些在线教程有相同的代码,并且运行良好。这里出了什么问题?
2个回答

27

你必须在布局中包含控件。

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="FormDemos.Views.Feedback">
    <ContentPage.Content>
      <StackLayout>
        <Label>I am Testimonials Page</Label>

        <ListView x:Name="FeedbackList" />
      </StackLayout>
    </ContentPage.Content>
</ContentPage>

我写了这篇小文章关于这个问题...


2
有时,当您使用绑定创建一个ListView时,如果您忘记添加Binding关键字,就会出现这种情况。
例如:{Binding Name}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接