无法从模型Xamarin Forms获取选定的Picker ID

时间:2018-10-17 07:17:06

标签: c# xamarin xamarin.forms

我对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");


    }

我得到的是MyProject.Models.CurrentStatus,而不是获得ID(我不想获得选定的值)。

有人可以帮我解决这个问题。

1 个答案:

答案 0 :(得分:1)

在实际上不知道您的HCImagePicker是什么样子的情况下,我猜想SelectedItem可能是对象类型。

因此,您需要强制转换并正确访问其属性:

CurrentStatus selectedStatus = (currentStatus.SelectedItem as CurrentStatus);
if (selectedStatus == null)
    return;
await DisplayAlert("TEST", "Id is"+ selectedStatus.id , "OK");

个人笔记: 帮自己一个忙,不要使用var。它可能很舒适并且使用起来很快,但是当涉及到任何类型的对象时,您肯定会感到困惑,因为您不知道最终会遇到哪种类型的类。

据我所知,使用var而不是适当的类型会使长期阅读和维护代码变得更加困难。另外,当强制转换出现错误时,您还可以更快地找到可能的错误源,因为编译器会警告您您尝试执行的操作是不可能的。