当绑定到POCO的列表时,指定的演员表无效 [英] Specified cast is not valid when binding to list of POCO's

查看:86
本文介绍了当绑定到POCO的列表时,指定的演员表无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好,所以我有以下观点:

Ok so I have the following view:

<?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="BoomSauce.MainPage">
  <ListView ItemsSource="{Binding Model.MyPocos}">
    <ListView.ItemTemplate>
      <DataTemplate>
        <Label Text="{Binding MyString}"></Label>
      </DataTemplate>
    </ListView.ItemTemplate>
  </ListView>
</ContentPage>

此视图的BindingContext是以下ViewModel:

The BindingContext of this view is the following ViewModel:

public class MainViewModel
{
    public MainModel Model { get; set; }
}

这是MainModel:

Here is MainModel:

public class MainModel
{
    public List<MyPoco> MyPocos { get; set; }
}

这是MyPoco:

public class MyPoco
{
    public string MyString { get; set; }
    public int MyInt { get; set; }
}

这是App()中发生的事情

Here's what's going on in App()

MainPage = new MainPage();

var viewModel = new MainViewModel
{
    Model = new MainModel
    {
        MyPocos = new List<MyPoco>()
        {
            new MyPoco() { MyInt = 1, MyString = "a" }, 
            new MyPoco() { MyInt = 2, MyString = "b" }, 
            new MyPoco() { MyInt = 3, MyString = "c" }, 
            new MyPoco() { MyInt = 4, MyString = "d" }, 
            new MyPoco() { MyInt = 5, MyString = "e" }
        }
    }
};

MainPage.BindingContext = viewModel;

真的没有别的了,我得到了以下异常:

Really nothing else to it, I am getting the following exception:

指定的演员表无效.

Specified cast is not valid.

但据我所知我做的一切正确,但没有内部异常,也没有更多的上下文.

But no inner exception and no more context, as far as I can tell I'm doing everything correctly.

绑定到字符串列表可以很好地工作,这是在我将其替换为任何其他对象时出现问题的原因.

Binding to a list of strings works fine, it's when I replace that with any other object that things go wrong.

关于我要去哪里的任何想法吗?

Any ideas on where I'm going wrong?

谢谢

推荐答案

原来,您不能将Label直接放在DataTemplate内,而必须将其嵌套在ViewCell中,就像这样:

It turns you can't put a Label directly inside a DataTemplate, you instead have to nest this in a ViewCell, like so:

<ViewCell>
    <ViewCell.View>
        <Label Text="{Binding MyString}" />
    </ViewCell.View>
</ViewCell>

神秘感解决了.

这篇关于当绑定到POCO的列表时,指定的演员表无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆