【问题标题】:Picker error "Specified cast is not valid" when getting the SelectedItem value in Xamarin Forms在 Xamarin Forms 中获取 SelectedItem 值时,选择器错误“指定的转换无效”
【发布时间】:2020-11-21 20:21:04
【问题描述】:

我有一个选择器,已经设置了绑定,但是当我尝试将 selecteditem 值复制到变量时,但显示错误“System.InvalidCastException:'Specified cast is not valid'。包含在选定项中的信息项目实际上是正确的,这是我的代码:

IDPisteroMainPage = Convert.ToInt32(pck_Pisteros.SelectedItem);

也试过这个(也没用,抛出了不同的错误):

IDPisteroMainPage = Convert.ToInt32(pck_Pisteros.SelectedItem as Pisteros);

Pisteros 是使用的模型。

错误:

我在 SelectedIndex 上也有同一个对象的绑定,但是这个仍然返回索引而不是我需要的 PisteroID,但是如果我使用以下内容:

IDPisteroMainPage = Convert.ToInt32(pck_Pisteros.SelectedIndex);

值确实被复制到变量中而没有问题

【问题讨论】:

  • SelectedItem != SelectedIndex

标签: c# xamarin binding picker selecteditem


【解决方案1】:

很难说出您真正想要什么或所涉及的类型。但是,它可能是您正在寻找的。​​p>

IDPisteroMainPage = Convert.ToInt32(((Pisteros)pck_Pisteros.SelectedItem).PisteroId);

// or slightly more fault tolerant if you expect a null 
if(pck_Pisteros.SelectedItem is Pisteros pisteros)
   IDPisteroMainPage = pisteros.PisteroId;
else
   // handle null (if need be)
   

// or if PisteroId is an int and SelectedItem is never null
IDPisteroMainPage = ((Pisteros)pck_Pisteros.SelectedItem).PisteroId

【讨论】:

    猜你喜欢
    • 2018-03-10
    • 2018-04-02
    • 2022-01-07
    • 2020-12-11
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多