Xamarin.Forms 2个DatePickers不要让结束日期为起始日期之前
问题描述:
我有一个绑定到一个对象从INotifyPropertyChanged的继承2个datepickers - 这里是在表单页面日期时间属性代码Xamarin.Forms 2个DatePickers不要让结束日期为起始日期之前
private DateTime _startDate;
public DateTime StartDate
{
get { return _startDate; }
set
{
if (DateTime.Compare(value, _startDate) == 0)
{
return;
}
_startDate = value;
OnPropertyChanged();
}
}
//public DateTime StartDate { get; set; }
private DateTime _endDate;
public DateTime EndDate
{
get { return _endDate; }
set
{
if (DateTime.Compare(value, _endDate) == 0)
{
return;
}
_endDate = value;
OnPropertyChanged();
}
}
public event PropertyChangedEventHandler PropertyChanged;
void OnPropertyChanged([CallerMemberName] string propertyName = null)
{
var handler = PropertyChanged;
if (handler != null)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
我有这个
DatePicker startDate = new DatePicker
{
BindingContext = uCoSafe,
Format = "D"
};
startDate.SetBinding(DatePicker.DateProperty, new Binding("StartDate", BindingMode.OneWayToSource));
startDate.PropertyChanged +=(sender, e) =>
{
uCoSafe.EndDate = uCoSafe.StartDate.AddDays(1);
};
MyCoLabel endDateLbl = new MyCoLabel(1, "End Date");
DatePicker endDate = new DatePicker
{
BindingContext = uCoSafe,
Format = "D"
};
endDate.SetBinding(DatePicker.DateProperty, new Binding("StartDate", BindingMode.TwoWay));
这一切工作正常。如果我更改开始日期,则更新结束日期。
我也想要它,如果结束日期是手动更改,那么它不能在开始日期之前设置。
我想这
endDate.PropertyChanged += (sender, e) =>
{
if (uCoSafe.EndDate.Date <= uCoSafe.StartDate.Date)
{
uCoSafe.EndDate = uCoSafe.StartDate.AddDays(1);
DisplayAlert("End Date Error", "End date cannot be earlier than the start date, please try again", "OK");
}
}
但当起始日期改变(当我不希望消息),而不是当结束日期的日期选择手动更改它才会触发。
任何建议,不胜感激
答
您的endDate
结合看起来是错误的。您写道:
endDate.SetBinding(DatePicker.DateProperty, new Binding("StartDate", BindingMode.TwoWay));
而且你可能是指:
endDate.SetBinding(DatePicker.DateProperty, new Binding("EndDate", BindingMode.TwoWay));
^^^^^^^^^
,这应该让你回到赛道上。
现在,我会做在这种情况下,而不是在错误的情况下显示警告,只是防止用户做出这样的错误,通过绑定endDate
的MinimumDateProperty
到uCoSafe.StartDate
。这可能会在最后提供更好的用户体验,恕我直言。
Doh !!!复制和粘贴的陷阱! Thankyou捡起来,也感谢MinimumDateProperty的建议,它完美的工作 – user1667474 2014-10-03 09:37:09
请记住,如果日期已经设置,更新MinimumDate不会“修复”日期,以考虑到这一点。您仍然需要在提交时进行验证。 – 2014-10-03 16:07:10
@AnthonyMills在选择器**上设置'MinimumDate'将**更新'Date'属性以确保'MinimumDate' 2014-10-03 20:00:05