Xamarin Picker SelectedItem Error指定的转换无效 [英] Xamarin Picker SelectedItem Error Specified cast is not valid

查看:118
本文介绍了Xamarin Picker SelectedItem Error指定的转换无效的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个已经设置了绑定的选择器,但是当我尝试将selecteditem值复制到变量时却显示错误"System.InvalidCastException:'指定的转换无效'.所选项目中包含的信息实际上是正确的,这是我的代码:

I have a picker, already set with the bindings, but when I'm trying to copy the selecteditem value to a variable but shows error "System.InvalidCastException: 'Specified cast is not valid'. The info contained in the selected item is actually correct, this is my code:

IDPisteroMainPage = Convert.ToInt32(pck_Pisteros.SelectedItem);

也尝试过此方法(也没有用,抛出了不同的错误):

also tried this (didn't work either, different error thrown tho):

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

Pisteros是使用的模型.

Pisteros being the model in used.

错误:

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

Also I have the binding for the same object on SelectedIndex, but this one still returns the index and not the PisteroID which is what I need, but if I use the following:

IDPisteroMainPage = Convert.ToInt32(pck_Pisteros.SelectedIndex);

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

the value does gets copied to the variable without issues

推荐答案

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

It's hard to tell what you actually want or the types involved. However, it could be you are looking for.

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

这篇关于Xamarin Picker SelectedItem Error指定的转换无效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆