我有两个日期选择器绑定到一个继承自INotifyPropertyChanged的对象 - 这是DateTime属性的代码
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");
}
}
但它仅在startDate更改时触发(当我不想要消息时),而不是在手动更改endDate的datepicker时触发。
任何建议都非常感谢
答案 0 :(得分:2)
endDate
的绑定看起来不对。你写道:
endDate.SetBinding(DatePicker.DateProperty, new Binding("StartDate", BindingMode.TwoWay));
你可能意味着:
endDate.SetBinding(DatePicker.DateProperty, new Binding("EndDate", BindingMode.TwoWay));
^^^^^^^^^
这会让你回到赛道上。
现在,在这种情况下我会做什么,而不是在出现错误时显示警告,只是通过绑定MinimumDateProperty
来阻止用户犯这样的错误。 endDate
uCoSafe.StartDate
。这可能会在最后提供更好的用户体验,仍然是恕我直言。