[英]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.HoId
为null
时,您不能调用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.