簡體   English   中英

有沒有辦法驗證 Xamarin forms 中的空控件選擇器(接收 integer 值)?

[英]Is there a way to validate an empty control picker (that receives an integer value) in Xamarin forms?

我是 Xamarin forms 的新手,我正在嘗試驗證控件選擇器。 當我提交時(如果我沒有 select 任何選項)我得到了錯誤:

System.NullReferenceException:“對象引用未設置為 object 的實例。”

下面是我嘗試做的一小部分。 但它有一些問題,任何輸入都會有幫助!

這是我的視圖模型的一部分:

public class MainOrderViewModel : BaseViewModel
{
    public Horarios _horarioId { get; set; }

    public MainOrderViewModel()
    {
        _horarioId = new Horarios();
    }

    public List<Horarios> Horario
    {
        get { return _horario; }
        set
        {
            _horario = value;
            OnPropertyChanged();
        }
    }

    public Horarios HorarioId
    {
        get { return _horarioId; }
        set
        {
            _horarioId = value;
            OnPropertyChanged();
        }
    }

    public ICommand SendToMainCommonOrderCommand => new Command(async () =>
    {
        if (String.IsNullOrEmpty(_horarioId.HoId.ToString()))
        {
                // Id value that I need with value Zero for simple validation
        }
    }
}

最后,我的觀點:

<Picker 
    ItemsSource="{Binding Horario}"
    ItemDisplayBinding="{Binding HoHorario,StringFormat='{0}:00hs'}"
    SelectedItem="{Binding HorarioId}"
    Title="Selecciona un horario de almuerzo"
    TextColor="Gray">
</Picker>

_horarioId.HoIdnull時,您不能調用ToString()方法。 這就是你得到例外的原因。

解決方案:

在調用ToString()之前檢查_horarioId.HoId是否為null

public ICommand SendToMainCommonOrderCommand => new Command(async () =>
{
    if (_horarioId.HoId == null)
    {
        //set the values here you want when _horarioId.HoId is null
        //for example
        _horarioId.HoId = "";
        //Or
        _horarioId.HoId = 0;
    }

    if (String.IsNullOrEmpty(_horarioId.HoId.ToString()))
    {
        //Id value that i need with value Zero for simple validation
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM