c# - 未从模型 Xamarin Forms 中获取选定的选取器 ID
问题描述
我对 Xamarin Forms 完全陌生。当用户要提交数据时,我想获取选定的选择器项目 ID。数据正在填充到选择器,没有任何问题。
模型类
public class CurrentStatus
{
public string id { get; set; }
public string current_status { get; set; }
}
public enum CurrentStatusId
{
NotApproved = 2,
Approved = 3,
Selected = 4,
NotSelected = 5
}
在我看来,我像这样限制了 ID。
<local:HCImagePicker x:Name="currentstatus" Title="Current Status" SelectedIndexChanged="HandleStatusItemChanged" SelectedItem="{Binding CurrentStatusId}" ItemsSource="{Binding CurrentStatuses}" ItemDisplayBinding="{Binding current_status}" HorizontalOptions="FillAndExpand" Margin="0,0,0,10" Image="arrowdown" ImageAlignment="Right" ImageHeight="8" ImageWidth="12">
</local:HCImagePicker>
提交数据后尝试获取 id (在这里我只是打印值)
public async void SubmitData(object sender, EventArgs e){
var selectedId = currentstatus.SelectedItem;
await DisplayAlert("TEST", "Id is"+ selectedId, "OK");
}
我没有得到一个 id(我不想得到选定的值),而是得到一个 MyProject.Models.CurrentStatus。
有人可以帮我解决这个问题。
解决方案
在不知道你的 HCImagePicker 的样子的情况下,我猜 SelectedItem 可能是对象类型。
因此,您需要对其进行强制转换并正确访问它的属性:
CurrentStatus selectedStatus = (currentStatus.SelectedItem as CurrentStatus);
if (selectedStatus == null)
return;
await DisplayAlert("TEST", "Id is"+ selectedStatus.id , "OK");
个人说明: 帮自己一个忙,不要使用 var。它使用起来可能很舒服和快速,但是当涉及到任何类型的对象时,你肯定会感到困惑,因为你不知道你最终会得到什么类型的类。
据我所知,使用 var 而不是正确的类型会使您的代码更难长期阅读和维护。此外,当转换出错时,您将能够更快地查明可能的错误源,因为编译器会警告您您尝试做的事情是不可能的。
推荐阅读
- python - 从列表中切片字符串时无法使用此条件 [python]
- asp.net - Azure ASP.NET REST API 和数据库部署
- r - ggplot2 使用列值作为图例
- mongodb - 如何有效地循环遍历 MongoDB 集合以更新序列列?
- amazon-web-services - AWS Amplify: AmplifyException 'You are not authorized to make this call.'
- python - NumPy fast iteration trough image
- python-3.x - Visual studio code Python execution
- r - R studio:分解/旋转数据框以计算每个组在不同时间段的每个变量的平均值
- perl - 如何做哈希参考切片的总和?
- python - 模型中的 Django 文件上传