Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Specified cast is not valid when binding to list of POCO's

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>

The BindingContext of this view is the following ViewModel:

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

Here is MainModel:

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

Here is MyPoco:

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

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?

Thanks

like image 897
JMK Avatar asked Mar 29 '15 16:03

JMK


1 Answers

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>

Mystery solved.

like image 124
JMK Avatar answered Nov 19 '22 07:11

JMK