【问题标题】:Specified cast is not valid when binding to list of POCO's绑定到 POCO 列表时,指定的强制转换无效
【发布时间】:2015-03-29 16:37:56
【问题描述】:

好的,所以我有以下观点:

<?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:

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

这里是 MainModel:

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

这是我的Poco:

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

这是 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;

真的没什么,我得到了以下异常:

指定的转换无效。

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

绑定到字符串列表可以正常工作,当我将其替换为任何其他对象时出现问题。

关于我哪里出错了有什么想法吗?

谢谢

【问题讨论】:

    标签: c# xaml xamarin xamarin.forms


    【解决方案1】:

    事实证明,您不能将 Label 直接放在 DataTemplate 中,而是必须将其嵌套在 ViewCell 中,如下所示:

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

    谜团解开了。

    【讨论】:

    • 您应该在 DataTemplate 中使用“TextCell”而不是“Label”,它应该可以工作。
    • @DavidKarlaš Label 对我有用,但应该我应该改用 Textcell 吗?
    • 不确定是否有任何性能差异...否则...如果有效,则无需更改;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-28
    • 2012-05-22
    • 2018-05-27
    • 2014-07-30
    • 2012-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多