选择器错误“指定的演员表无效"在 Xamarin Forms 中获取 SelectedItem 值时 [英] Picker error "Specified cast is not valid" when getting the SelectedItem value in Xamarin Forms
问题描述
我有一个选择器,已经设置了绑定,但是当我尝试将 selecteditem 值复制到变量时,却显示错误System.InvalidCastException: 'Specified cast is not valid'.所选项目中包含的信息实际上是正确的,这是我的代码:
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
推荐答案
很难说出您真正想要什么或涉及的类型.但是,它可能是您正在寻找的.p>
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 Forms 中获取 SelectedItem 值时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!