在 Xamarin Forms 中获取 SelectedItem 值时选择器错误 "Specified cast is not valid"

Picker error "Specified cast is not valid" when getting the SelectedItem value in Xamarin Forms

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

IDPisteroMainPage = Convert.ToInt32(pck_Pisteros.SelectedItem);

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

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

使用的模型是 Pisteros。

错误:

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

IDPisteroMainPage = Convert.ToInt32(pck_Pisteros.SelectedIndex);

值确实被毫无问题地复制到变量

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

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