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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With